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字符串,可以
A.不必反序列化市第一像下面
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);
仔細查看@ Tar_Tw45設置的問題和限制。 – Sevle