问题:解析来自 Foursquare Venues API 的以下响应:
{
meta: {
code: 200
}
notifications: [
{
type: "notificationTray"
item: {
unreadCount: 0
}
}
]
response: {
venues: [
{
id: "5374fa22498e33ddadb073b3"
name: "venue 1"
},
{
id: "5374fa22498e33ddadb073b4"
name: "venue 2"
}
],
neighborhoods: [ ],
confident: true
}
}
The GSON文档网站建议使用 GSON 的解析 API 将响应解析为 JSONArray,然后将每个数组项读入适当的对象或数据类型(示例here)。因此,我最初改用以下实现:
JsonParser parser = new JsonParser();
try {
JSONObject json = new JSONObject(response);
JSONArray venues = json.getJSONObject("response").getJSONArray("venues");
int arraylengh = venues.length();
for(int i=0; i < arraylengh; i++){
Log.d(TAG, "The current element is: " + venues.get(i).toString());
}
}
catch(JSONException e){
}
上面的代码给了我一个包含所有“场地”的 JSONArray。下一个问题是我不知道如何将“venues”JSONArray 解析/转换为 ArrayList(对于我的自定义 Venue 对象)。
解决方案:正如 JohnUopini 回答中所述,我能够使用以下实现成功解析 JSON:
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
JsonParser parser = new JsonParser();
JsonObject data = parser.parse(response).getAsJsonObject();
Meta meta = gson.fromJson(data.get("meta"), Meta.class);
Response myResponse = gson.fromJson(data.get("response"), Response.class);
List<Venue> venues = Arrays.asList(myResponse.getVenues());
使用上面的代码,我能够成功地将“元”以及“响应”JSON 属性解析到我的自定义对象中。
作为参考,下面是我的 Response 类(注意:这些属性被定义为公共用于测试目的。最终的实现应该将这些属性声明为私有并使用 setter/getter 进行封装):
public class Response {
@SerializedName("venues")
public Venue[] venues;
@SerializedName("confident")
public boolean confident;
Response(){}
}
注意/反馈:在实施接受的答案的建议后,我在调试过程中多次遇到以下(或类似的)异常消息:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT
我收到上述异常的原因是因为“venues”JSON 中某些子对象的“类型”与我在自定义 Venue 类中定义此类对象的“类型”不匹配。确保自定义类中的类型与 JSON 具有一一对应关系(即 [ ] 是数组属性,{ } 是对象属性等)。