当我调用服务器时,它的响应基于 json 对象。实际上,我知道如何解析 JSON 对象,但这个响应对我来说很奇怪。服务器响应是:
{"body":"Not Available!","clazz":"SoccerMatchPreview","id":{"inc":-2024241794,"machine":415106952,"new":false,"time":1337861978000,"timeSecond":1337861978},"publishedDate":"2012-06-08 17:00:00 +0100","refKey":"SoccerMatchPreview_4fb897be18be8b87f9117595","title":"Poland vs Greece"}
我需要的那些信息是 body、publishedDate、refKey 和 title。我基于 JSON 对象编写的代码是这样的:
JSONObject jObject = new JSONObject(response);
JSONArray contestantObjects = jObject.getJSONArray("id");
for(int i=0; i<contestantObjects.length(); i++) {
mPreview.setBody(contestantObjects.getJSONObject(i).getString("body").toString());
mPreview.setPublishedDate(contestantObjects.getJSONObject(i).getString("publishedDate").toString());
mPreview.setRefKey(contestantObjects.getJSONObject(i).getString("refKey").toString());
mPreview.setTitle(contestantObjects.getJSONObject(i).getString("title").toString());
}
但是因为它没有“[]”,所以我认为它不是 JSON 对象。因此,我编写了另一个基于代码的 JSON 数组。
JSONArray contestantObjects = new JSONArray(response);
for(int i=0; i<contestantObjects.length(); i++) {
mPreview.setBody(contestantObjects.getJSONObject(i).getString("body").toString());
mPreview.setPublishedDate(contestantObjects.getJSONObject(i).getString("publishedDate").toString());
mPreview.setRefKey(contestantObjects.getJSONObject(i).getString("refKey").toString());
mPreview.setTitle(contestantObjects.getJSONObject(i).getString("title").toString());
}
但结果相同,Logcat 显示:
值 {"id":{"timeSecond":1337861978,"time":1337861978000,"new":false,"machine":415106952,"inc":-2024241794},"body":"不可用!"," org.json 类型的标题":"波兰 vs 希腊","publishedDate":"2012-06-08 17:00:00 +0100","clazz":"SoccerMatchPreview","refKey":"SoccerMatchPreview_4fb897be18be8b87f9117595"}。 JSONObject 无法转换为 JSONArray
任何建议将不胜感激。谢谢