Default Value when deserialized?

6,351 views
Skip to first unread message

shaunpatterson

unread,
Jun 21, 2012, 12:04:27 PM6/21/12
to googl...@googlegroups.com
I have an object defined like this:

public class Test {
    public String string1 = "";
    public List<String> list1 = new ArrayList<String>();
}

And this object is built from the following JSON:

{ "string1" : "This is a test" }

When deserialized, list1 is null.  Is there a way to have Gson ignore missing values?  I want list1 to be an empty ArrayList if the value is not passed in the JSON.

Thanks

--
Shaun

shaunpatterson

unread,
Jun 22, 2012, 2:07:40 PM6/22/12
to google-gson
It seems adding

public Test() {
this.string1 = "default value";
this.list1 = new ArrayList<String>();
}

seems to do the trick. Is this the proper way of doing this?

--
Shaun

Brandon Mintern

unread,
Jun 22, 2012, 9:23:10 PM6/22/12
to googl...@googlegroups.com
If your class has a default constructor (even an empty one), your
first pattern (initializing the instances variables where they are
defined instead of in the constructor) should work fine. If your class
does not have a default constructor, I believe (I could be wrong) that
Gson manually tries to allocate the object, which would skip any
initialization at all. This will actually fail on some platforms (I
have seen posts to that effect about Android allocations failing).

So you should always make sure Gson-constructed classes have a default
constructor. It may be that putting the code you showed in the default
constructor worked not because you moved the code around, but because
you had a default constructor at all.
> --
> You received this message because you are subscribed to the Google Groups "google-gson" group.
> To post to this group, send email to googl...@googlegroups.com.
> To unsubscribe from this group, send email to google-gson...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/google-gson?hl=en.
>

Roberto Andrade

unread,
Jun 18, 2013, 6:34:45 PM6/18/13
to googl...@googlegroups.com
I've tried both inline and in the default constructor but in my case the default value keeps being overwritten with null.

In my particular case I do have { list1: null } in the json. Any way to prevent that from overriding the default value or specifying what default values to use for certain fields in the case of null via annotations or a custom TypeAdapter/Deserializer?
Reply all
Reply to author
Forward
0 new messages