简体   繁体   中英

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?

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

It is better to use Pojo for formatting.

class Wrapper{
 private List<Data> data;
 // geters, seters
}
class Data{
 private String content;
 private List<Integer> positions;
 // geters, seters
}

For deserialization/serealization you can use Jackson

ObjectMapper mapper = new ObjectMapper();
Wrapper wriper = mapper.readValue(dataString, Wrapper.class);
String jsonString = mapper.writeValueAsString(wriper);

or Gson

Gson gson = new Gson();
Wrapper wriper = gson.fromJson(dataString, Wrapper.class);
String json = gson.toJson(wriper);

you can use gson JsonElement as the contianer object that will contain JsonElements like JsonObject or JsonArray

https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonElement.html

Without POJO, this seems to solve the nested JSON solution using Gson

package com.test;

import com.google.gson.JsonObject;

public class Main {

    public static void main(String[] args) {
        
        JsonObject ex3 = new JsonObject();
        ex3.addProperty("example3", 30);
        
        JsonObject ex2 = new JsonObject();  
        ex2.add("example2", ex3.getAsJsonObject());
        
        JsonObject ex1 = new JsonObject();  
        ex1.add("example1", ex2.getAsJsonObject());
        
        System.out.println(ex1.toString());
    }       
}

The output is:

{"example1":{"example2":{"example3":30}}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM