使用GSON反序列化嵌套数组

时间:2016-03-07 15:39:31

标签: android json gson

给予

JSON

// imagine this is JSON of a city
{
    "title" : "Troy"
    "people" : [
        {
            {
                "title" : "Hector",
                "status" : "Dead"
            },
            {
                "title" : "Paris",
                "status" : "Run Away"
            }
        },
        ...
    ],
    "location" : "Mediteranian",
    "era" : "Ancient",
    ...
}

城市

public class City {
    @SerializeName("title")
    String title;
    @SerializeName("people")
    List<Person> people;
    @SerializeName("location")
    String location;
    @SerializeName("era")
    String era;
    ...
}

public class Person {
    @SerializeName("title")
    private String title;
    @SerializeName("status")
    private String status;
}

如果上面有JSON字符串,则可以创建人员列表

一个。无需像以下那样首先反序列化城市

City city = new Gson().fromJson(json, City.class)
ArrayList<Person> people = city.people;

并且

B中。无需将字符串转换为JSONObject,获取JSONArray然后转换回字符串,如下面的

String peopleJsonString = json.optJSONArray("people").toString
ArrayList<Person> people = new Gson().fromJSON(peopleJsonString, Person.class);

2 个答案:

答案 0 :(得分:4)

您可以使用自定义JsonDeserializer,它是Gson(com.google.gson.JsonDeserializer)的一部分。

简单示例:

public class WhateverDeserializer implements JsonDeserializer<Whatever> {
  @Override
  public Whatever deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
    Whatever whatever = new Whatever();
    // Fetch the needed object here
    // whatever.setNeededObject(neededObject);
    return whatever;
  }
}

然后您可以像这样应用此反序列化器:

Gson gson = new GsonBuilder()
            .registerTypeAdapter(Whatever.class, new WhateverDeserializer())
            .create();

此页面上有一个完整的示例,说明如何使用自定义反序列化器,包括超级详细说明:http://www.javacreed.com/gson-deserialiser-example/

答案 1 :(得分:0)

我不认为你可以直接获取列表而不解析json数组。你需要解析数组。通过Gson会更快;

如果你严格需要(只有数组)并且你不会使用任何其他json对象。只需删除它们,这样gson就不会解析它们。