Creating nested JSON objects with different formats in Java with GSON

gson deserialize nested objects
gson serialize nested objects
convert nested json to java object using jackson
gson custom deserializer
gson annotations
gson flatten json
gson deserialize nested class
gson read json file to jsonobject

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

Gson, 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] }  Some of you might have come to a different result. Creating the Java objects is not always unambiguous. For example, based on the JSON, we see that the cook and waiter nested objects have the same structure. You could still create a different class, like we did above, or make a general Staff class for both:

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

Gson tutorial, If you're interested in other topics, check out our series outline: Getting Started with Java-JSON Serialization & Deserialization; Mapping of Nested Objects Your browser does not currently recognize any of the video formats available. Gson correctly created the nested userAddress JSON object. Tag: java,arrays,json,gson I'm getting a response from Elasticsearch in JSON format that I'd like Gson to convert into a Java class, however I'm having trouble wrapping my head about how to develop the class.

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);

Gson - Quick Guide, These are Gson features: Simple tools for Java object JSON serialization and deserialization. GsonBuilder can be used to build Gson with various configuration settings. A list of car objects is serialized into JSON format. If we want to use different name for java bean and json, then we can use @SerializedName java annotation and map the variables in JSON and Java Class. Gson Example. Let’s look at a complex Gson example that involves nested object and array in JSON and we will map it to java bean properties of type List, Map, Array etc.

Two ways to use Gson for JSON in Java, Learn to convert object to json; and convert json to java object. There are some other java libraries also capable of doing this conversion, but Gson stands among very few which Convert Java objects to JSON format 4. In most of the cases, Gson library is smart enough to create instances even if any class does not  JSON Data Types – OBJECT In JSON, an object datatype has the following properties. • It is JSON data type which is represented as an unordered collection of key and value pairs. • Objects are enclosed with in the curly braces i.e. it starts with ‘{‘ and ends with ‘}’.

JSON handling with org.json / Create nested JSON object / Essential , Despite its shortcomings, JSON is the most common format for APIs on the web Gson allows you to read JSON into a tree model: Java objects that get a JsonElement which can be descended through to retrieve nested values. or you need to create objects from JSON that you can pass to other code,  Java Google Json (Gson) New in Gson 2.3 September 12, 2016 September 22, 2016 Mithil Shah 0 2 thoughts on “ Java Google Json (Gson) Serializing Inner classes ”

Gson Tutorial, JSON handling with org.json / Create nested JSON object / Essential Android. JSON SerializationDeserialization with AutoValue and Gson · Updating the 35 Supporting different screen resolutions. 36 Glide. 37 Retrofit2. 38 Dialog. 39 ACRA. 40 GreenDAO. 41 Formatting Strings 199 Java Native Interface (JNI). Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Comments
  • you can just use this two pojo: ´class Wrapper { public String content; public List<Integer> positions}´ and ´class Response { public List<Wrapper> wrapper}´
  • That's a lot of boilerplate... I don't need JSON anywhere else in the program, not sure if that's the best approach here. But it should work for a start!
  • It all depends on what you want to achieve. For me working with POJO models in easier. Another approach would be to use JsonElement objects and traverse it that way.