Format of POJO for nested JSON?

So lets say the JSON response is:

[{ "data" : { "item1": value1, "item2:" value2 }}]

How do you get the values 'value1' and 'value2' when you must first access data?

If the fields were at the root then I could just have the method return a POJO with those field names.


I basically want the below to work.

@GET("/path/to/data/")
Pojo getData();

class Pojo
{
public String item1;
public String item2;
}

Answers


You can try below code to convert your json string to Pojo object with required fields using Gson library.

Gson gson = new Gson();

JsonArray jsonArray = gson.fromJson (jsonString, JsonElement.class).getAsJsonArray(); // Convert the Json string to JsonArray

JsonObject jsonObj = jsonArray.get(0).getAsJsonObject(); //Get the first element of array and convert it to Json object

Pojo pojo = gson.fromJson(jsonObj.get("data").toString(), Pojo.class); //Get the data property from json object and convert it to Pojo object

or you can define your nested Pojo class to parse it.

class Pojo
{
    private String item1;
    private String item2;

    //Setters and Getters
}

class Data
{
    private Pojo data;

    //Setters and Getters
}

ArrayList<Data> yourArray = new Gson().fromJson(jsonString, new TypeToken<List<Data>>(){}.getType());

EDIT : Try below code to get value1 and value2 using Retrofit.

class Pojo
{
    private String item1;
    private String item2;

    //Setters and Getters
}

class Data
{
    private Pojo data;

    //Setters and Getters
}

class MyData
{
    private ArrayList<Data> dataList;

    //Setters and Getters
}

IService service = restAdapter.create(IService.class);
MyData data = service.getData(); 

ArrayList<Data> list = data.getDataList(); // Retrive arraylist from MyData

Data obj = list.get(0); // Get first element from arraylist

Pojo pojo = obj.getData(); // Get pojo from Data 

Log.e("pojo", pojo.item1 + ", " + pojo.item2);

Need Your Help

Floating point binary representation

floating-point bit-representation

I have a problem understading a floating point representation(Two's placement-sign mantissa exponent), could you check, am I doing right?

What are the disadvantages of using persistent connection in PDO

php pdo

In PDO, a connection can be made persistent using the PDO::ATTR_PERSISTENT attribute. According to the php manual -