Search code examples
javajsongson

Creating nested JSON objects with different formats in Java with GSON


I'm 100% certain this has been asked a million times already, but I'm really unsure how to properly approach this. I haven't done a lot with JSON or serializing it yet.

Basically, this is what I want to create using GSON:

{
    "wrapper" : [
        {
            "content": "loremipsum",
            "positions": [0,3]
        },
        {
            "content": "foobar",
            "positions": [7]
        },
        {
            "content": "helloworld"
        }
    ]
}

Breaking it down, we've got a field for an array, containing objects which in themselves contains two fields, one of which maps to a string and the other to yet another array that can contain an unknown amount of integers or can be missing entirely.

I can't even begin to imagine how to get this result with GSON. So far my idea would be to have everything be in a Map<String, List<Map<String, Object>>> beast and convert it, but that Object bothers me because it could either be a String or a List in this particular case. There could be casts, but that sounds like a stupidy complex thing for something that would look easier if I even just manually typed it in a String.format() or similar.

Isn't there a simpler way of handling this stuff?


Solution

  • I would go with creating some POJO class for your Data :

    class MyData {
        private List<Data> wrapper;
    
        //getters setters constructors
    }
    
    class Data {
        private String content;
        private List<Integer> positions;
    
        //getters setters constructors
    }
    

    And then for deserializing it :

    Gson gson = new Gson();
    String json = //json here
    MyData myData = gson.fromJson(myJson, MyData.class);
    

    And for serializing :

    MyData myData = ...
    String json = gson.toJson(myData);
    

    Another way could be parsing this structure using JsonParser and access its elements :

    JsonParser jsonParser = new JsonParser();
    JsonElement jsonElement = jsonParser.parse(json);
    JsonElement wrapperElement = jsonElement.getAsJsonObject().get("wrapper"); //access wrapper
    JsonArray array = wrapperElement.getAsJsonArray(); // access array