java-嵌套JSON的POJO格式?

因此,可以说JSON响应为:

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

当您必须首先访问数据时,如何获得值“ value1”和“ value2”?

如果字段位于根目录,那么我可以让该方法返回带有这些字段名称的POJO.

我基本上希望下面的工作.

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

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

解决方法:

您可以尝试以下代码,使用Gson库将JSON字符串转换为具有必填字段的Pojo对象.

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

或者,您可以定义嵌套的Pojo类来解析它.

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

编辑:尝试下面的代码以使用翻新获取value1和value2.

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);
上一篇:java-JSON中选定键的掩码值


下一篇:如何在Java中将hashmap的哈希值转换为json