2011-11-06 75 views
2

我有一個JSON字符串,如下所示。這來自我在Android應用程序中使用的網站(下面的URL輸出到一個頁面)。在一個對象中反序列化與Gson的JSON

{"posts": [{"id":"0000001","longitude":"50.722","latitude":"-1.87817","position":"Someplace 1","altitude":"36","description":"Some place 1 "},{"id":"0000002","longitude":"50.722","latitude":"-1.87817","position":"Some PLace 2","altitude":"36","description":"Some place 2 description"}]} 

我想反序列化到一個列表,我可以通過他們以後的應用迭代這一點。我該怎麼做呢?我創建了一個類,其屬性和方法以及List類如下,然後使用fromJson對其進行反序列化,但它返回NULL。希望這個問題很清楚,並提前感謝。

ListClass

包數據訪問;

import java.util.List; 

public class LocationList { 
    public static List<Location> listLocations; 

    public void setLocationList(List <Location> listLocations) { 
     LocationList.listLocations = listLocations; 
    } 

    public List<Location> getLocationList() { 
     return listLocations; 
    } 
} 

GSON

public LocationList[] getJsonFromGson(String jsonURL) throws IOException{ 
    URL url = new URL(jsonURL); 
    String content = IOUtils.toString(new InputStreamReader(url.openStream())); 
    LocationList[] locations = new Gson().fromJson(content, LocationList[].class); 

    return locations; 
} 

回答

2

您嘗試反序列化到LocationList對象的數組 - 這肯定不是你的意圖,是嗎? json片段不包含列表列表

我會放棄類LocationList(除了它應該在將來被擴展?),並使用純List。然後,你必須創建一個類型的令牌是這樣的:

java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<ArrayList<Location>>() {}.getType(); 
List<Location> locations = new Gson().fromJson(content, type); 
+0

感謝回答。 Type和TypeToken的命名空間是什麼? – Chin

+0

java.lang.Type java.lang.Type和com.google.gson.reflect.TypeToken – Yogu

+0

eclipse flags java.lang.Type as invalid。但是,import java.lang.reflect.Type;很好。那是你的意思? – Chin

2

,如果只能這樣JSON響應可以使用本地類解析,這裏是同一個解決方案:

String strJsonResponse="Store response here"; 
JsonObject obj = new JsonObject(strJsonResponse); 
JsonArray array = obj.getJsonArray("posts"); 

for(int i=0; i<array.length; i++) 
{ 
    JsonObject subObj = array.getJsonObject(i); 
    String id = subObj.getString("id"); 
    String longitude = subObj.getString("longitude"); 
    String latitude = subObj.getString("latitude"); 
    String position = subObj.getString("position"); 
    String altitude = subObj.getString("altitude"); 
    String description = subObj.getString("description"); 

    // do whatever procedure you want to do here 
}