2011-11-06 52 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 
}