我正在使用Gson来创建和解析JSON,但是我遇到了一个问题。在我的代码中,我使用了这个字段:
@Expose
private ArrayList<Person> persons = new ArrayList<Person>();
但我的JSON格式是这样的:
persons:{count:"n", data:[...]}
数据是一个人的数组。
有没有办法使用 Gson 将这个 JSON 转换成我的类?我可以使用 JsonDeserializer 吗?
您需要一个定制的反序列化程序(http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonDeserializer.html),例如:
public static class MyJsonAdapter implements JsonDeserializer<List<Person>>
{
List<Person> people = new ArrayList<>();
public List<Person> deserialize( JsonElement jsonElement, Type type, JsonDeserializationContext context )
throws JsonParseException
{
for (each element in the json data array)
{
Person p = context.deserialize(jsonElementFromArray,Person.class );
people.add(p);
}
}
return people;
}
String jsonInputStr = "{count:"n", data:[...]}";
Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson(jsonInputStr, JsonElement.class).getAsJsonObject();
List<Person> persons = gson.fromJson(jsonObj.get("data").toString(), new TypeToken<List<Person>>(){}.getType());