How to extract multiple objects from JSON using Gson

Nodir Nasirov :

There is a json file with multiple objects:

{
    "object1": {
        "property": "bar",
    },
    "object2": {
        "property": "foo",
    },
    "object3": {
        "property": "buzz"
    }
}

There are 3 classes as well, Object1, Object2 and Object3, how can I extract all 3 as separate objects?

This obviously did not work:

Object1 = gson.fromJson(reader, Object1.class);
Object2 = gson.fromJson(reader, Object2.class);
Object3 = gson.fromJson(reader, Object3.class);
Deadpool :

You just need a wrapper class with these three properties

public class Wrapper {

 private Object1 object1;

 private Object2 object2;

 private Object3 object3;

  // getters and setters

}

And then use gson.fromJson to parse json into Wrapper

Wrapper wrapper = gson.fromJson(reader, Wrapper.class);

From Wrapper get all the required attributes

Object1 object1 = wrapper.getObject1();
Object2 object2 = wrapper.getObject2();
Object3 object3 = wrapper.getObject3();

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=421022&siteId=1