Skip to content
Advertisement

Write java class with nested Map to custom json format using Gson

What Java data structure can be used to serialize to the following Json which have a set of child objects?

Example:

JavaScript

Writing John and Paul can be done by: Map<String,Person> but i cannot figure out how to nest the Child without having the ‘children’ property.

Example:

JavaScript

I am not sure it is relevant, but Gson is being used to create the Json file

Advertisement

Answer

I’m not sure wheher this is possible with GSON though it’s possible with Jackson.

With GSON you can try custom JsonSerializer, which might look something like this:

JavaScript

and register to GSON instance like this:

JavaScript

Note that code assumes that both type "Person" and "child" are represented by the same Person class. It should be pretty easy to modify this if not.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement