Fwd: Handling optional, non-present lists: JSON contains empty lists by default

14 views
Skip to first unread message

Steffen Dettmer

unread,
Jun 22, 2018, 12:44:00 PM6/22/18
to jsonschema...@googlegroups.com
Hi,

in one schema we have multiple optional lists, as artificial example:

"Type": {
"properties": {
"AList": {
"type": "array",
"items": { ... }
},
"BList": {
"type": "array",
"items": { ... }
},
required: []
}
}

They are optional, normally not present in the JSON on wire. If
they are not present, in JSON it looks like:

"Type": { }

GSON-annotated generated class contains:

class Type {
@SerializedName("AList")
@Expose
private List<AList> aList = new ArrayList<AList>();

@SerializedName("BList")
@Expose
private List<BList> bList = new ArrayList<BList>();
}

and happily parses this, but the resulting Type instance then has
two zero-length lists:

Type instance = gson.fromJson(json);
Assert.assertNotNull(instance.getAList());
Assert.assertEquals(0, instance.getAList().size());

instead of being null, when encoding / serializing this leads to:

"Type": { "AList": [], "BList": [] }

which is not the same as the input was.

I hope I explained well what my issue / question is about.

We can easily fix this (e.g. instance.setAList(null)), but I
wonder why this behavior is correct and expected or if we do
anything wrong.

Am I generally correct that I expect:

Type instance = new Type();
String json = gson.toJson(instance);

to produce:

"Type": { }

or is including the two empty lists actually correct / required
by some standard?

Technically it could be fixed by initializing the members to null
instead of new ArrayList<BList>() I think. Is this true?

Any hints or thoughts?

Best regards,
Steffen

Joe Littlejohn

unread,
Jun 25, 2018, 10:07:09 AM6/25/18
to jsonschema...@googlegroups.com
Hi Steffen

You can use initializeCollections = false to turn off these empty lists.

Cheers

Joe

--
You received this message because you are subscribed to the Google Groups "jsonschema2pojo-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jsonschema2pojo-...@googlegroups.com.
Visit this group at https://groups.google.com/group/jsonschema2pojo-users.
For more options, visit https://groups.google.com/d/optout.

Steffen Dettmer

unread,
Jun 27, 2018, 10:23:28 AM6/27/18
to jsonschema...@googlegroups.com
* On Mon, Jun 25, 2018 at 4:06 PM, Joe Littlejohn
<joelit...@gmail.com> wrote:
> You can use initializeCollections = false to turn off these empty lists.

Ohh. So easy it is.
Sorry that I didn't read the documentation carefully enough, and
thanks so much again for your help!

Steffen
Reply all
Reply to author
Forward
0 new messages