3

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;
}
Purushotham
  • 3,770
  • 29
  • 41
rodly
  • 149
  • 3
  • 14

1 Answers1

4

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);
Purushotham
  • 3,770
  • 29
  • 41
  • How do I get the json string when using Retrofit? – rodly Mar 06 '14 at 19:17
  • 1
    @RodL. As per Retrofit [documentation](http://square.github.io/retrofit/), Retrofit uses [Gson](https://code.google.com/p/google-gson/) by default to convert HTTP bodies to and from JSON. If you want to specify behavior that is different from Gson's defaults (e.g. naming policies, date formats, custom types), provide a new Gson instance with your desired behavior when building a RestAdapter. – Purushotham Mar 07 '14 at 04:00
  • @RodL. I am not familiar with Retrofit – Purushotham Mar 07 '14 at 04:15