2016-03-07 53 views
1

給予使用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字符串,可以

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

回答

2

您可以使用Gson(com.google.gson.JsonDeserializer)的一部分的自定義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/

0

我不認爲你可以直接得到列表而不解析json數組。你需要解析數組。通過Gson會更快;

如果你嚴格需要(只有數組),你不會使用任何其他的json對象。只需刪除它們,這樣gson就不會解析它們。

+0

仔細查看@ Tar_Tw45設置的問題和限制。 – Sevle