{
"status":1,
"list":
{
"218888771":
{
"item_id":"218888771",
"title":"twitter",
"url":"http:\/\/t.co\/oFYGY7z0",
"time_updated":"1347094862",
"time_added":"1347094862",
"state":"0"
},
"217345740":
{
"item_id":"217345740",
"title":"",
"url":"http:\/\/t.co\/dCvNwtrK",
"time_updated":"1346790837",
"time_added":"1346790700",
"state":"0"
}
},
"since":1347094862,
"complete":1
}
我正在使用谷歌GSon,但没有真正到达任何地方。
首先,我很困惑为什么我无法将其转换为JsonArray。 “list”看起来像一个json数组。但它似乎没有用。我不介意使用POJO方法,但我如何首先解析这个JSONArray?
JsonParser parser = new JsonParser();
JsonElement tradeElement = parser.parse(response);
JsonObject trade = tradeElement.getAsJsonObject();
json.get("list").getAsJsonObject().get("url")
这让我无效。
答案 0 :(得分:1)
{
"complete":1,
"list":{
"217345740":{
"item_id":"217345740",
"state":"0",
"time_added":"1346790700",
"time_updated":"1346790837",
"title":"",
"url":"http://t.co/dCvNwtrK"
},
"218888771":{
"item_id":"218888771",
"state":"0",
"time_added":"1347094862",
"time_updated":"1347094862",
"title":"twitter",
"url":"http://t.co/oFYGY7z0"
}
},
"since":1347094862,
"status":1
}
正如您所看到的那样,格式良好list
是一个具有两个属性217345740
和218888771
的对象。数组括在括号[]
中。这就是你无法将它作为数组投射的原因。
您最好的选择是正确使用gson及其将json解析为POJO的能力。 这是完全未经测试的(我没有那么多,我不在我的开发机器上),但你会看到这个想法。
public class Item {
long item_id;
int state;
@SerializedName("time_added")
Date timeAdded;
@SerializedName("time_updated")
Date timeUpdated;
String title;
String url;
// getter & setters
}
public class Trade {
int complete;
Date since;
int status;
Map<Long, Item> list;
// getter & setters
}
public class Foo {
public static void main(String[] args) {
String json = "";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
});
Gson gson = builder.create();
Trade trade = gson.fromJson(json, Trade.class);
Map<Long, Item> items = trade.getList();
System.out.println(items.get(217345740L).getUrl()); // should print http://t.co/dCvNwtrK
}
}
答案 1 :(得分:0)
JSON数组如下:
[
{
"item_id":"218888771",
"title":"twitter",
"url":"http:\/\/t.co\/oFYGY7z0",
"time_updated":"1347094862",
"time_added":"1347094862",
"state":"0"
},
{
"item_id":"218888771",
"title":"twitter",
"url":"http:\/\/t.co\/oFYGY7z0",
"time_updated":"1347094862",
"time_added":"1347094862",
"state":"0"
},
]
以上是地图的JSONArray。由于您的数据是地图地图,因此您应该使用适当的键浏览地图,并获取具有“url”键的最内部地图。