2011-04-26 57 views
18

因此,我使用GSON從API解析JSON,並堅持如何讓它解析數據中的動態字段。如何使用GSON解析動態JSON字段?

下面是查詢返回的JSON數據的例子:

{ 

- 
30655845: { 
    id: "30655845" 
    name: "testdata 
    description: "" 
    latitude: "38" 
    longitude: "-122" 
    altitude: "0" 
    thumbnailURL: http://someimage.com/url.jpg 
    distance: 9566.6344386665 
} 
- 
28688744: { 
    id: "28688744" 
    name: "testdata2" 
    description: "" 
    latitude: "38" 
    longitude: "-122" 
    altitude: "0" 
    thumbnailURL: http://someimage.com/url.jpg 
    distance: 9563.8328713012 
} 
} 

我目前正在處理一個靜態值的方法是使用一類:

import com.google.gson.annotations.SerializedName; 

public class Result 
{ 
@SerializedName("id") 
public int id; 

@SerializedName("name") 
public String name; 

@SerializedName("description") 
public String description; 

@SerializedName("latitude") 
public Double latitude; 

@SerializedName("longitude") 
public Double longitude; 

@SerializedName("altitude") 
public Double altitude; 

@SerializedName("thumbnailURL") 
public String thumbnailURL; 

@SerializedName("distance") 
public Double distance; 
} 

,然後我可以簡單地用GSON解析:

Gson gson = new Gson(); 

Reader reader = new InputStreamReader(source); 

Result response= gson.fromJson(reader, Result.class); 

我知道這對子數據有效,因爲我可以查詢並得到單個條目並且很容易解析,但是對於數組中每個值給出的隨機整數值呢? (即30655845和2868874)

任何幫助?

回答

19

根據GSON documentation,你可以做這樣的事情:

Type mapType = new TypeToken<Map<Integer, Result> >() {}.getType(); // define generic type 
Map<Integer, Result> result= gson.fromJson(new InputStreamReader(source), mapType); 

或者你可以嘗試寫custom serializer爲你的類。免責聲明:我也是,沒有使用GSon的經驗,但有其他框架如傑克遜。

+1

釘牢它,這工作完美無瑕。非常感謝。 :D – 2011-04-27 21:51:08

+0

有什麼辦法解析相同的,但使用牛頓軟件? – 2016-05-19 09:14:51