我有一个如下所示的 JSON 字符串。它来 self 在 Android 应用程序中使用的网站(下面的 URL 输出到页面)。
{"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。希望问题很清楚,非常感谢。
列表类
封装数据访问;
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;
}
最佳答案
您尝试反序列化为 LocationList 对象数组 - 这肯定不是您的 Intent ,不是吗? json fragment 不包含列表列表。
我会放弃 LocationList 类(除非它将来应该扩展?),并使用纯列表。然后,您必须创建一个如下所示的类型标记:
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<ArrayList<Location>>() {}.getType();
List<Location> locations = new Gson().fromJson(content, type);
关于android - 在对象中使用 Gson 反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8028336/