我正在尝试解析Android中的JSON文档,我之前已经能够使用相同的逻辑进行解析。但在网站的这一部分我的代码似乎打破了,我花了好几个小时试图比较发生了什么变化,但我不知道。我在这里缺少什么?
有人可以告诉我为什么我的尝试失败了吗?
目标JSON
[ { "data" : { "after" : null,
"before" : null,
"children" : [ { "data" : { "approved_by" : null,
"author" : "BuzzAldrinHere",
"author_flair_css_class" : null,
"author_flair_text" : null,
"banned_by" : null,
"clicked" : false,
"created" : 1404871393.0,
"created_utc" : 1404842593.0,
"distinguished" : null,
"domain" : "self.IAmA",
"downs" : 0,
"edited" : 1404849572.0,
"gilded" : 0,
"hidden" : false,
"id" : "2a5vg8",
"is_self" : true,
"likes" : null,
"link_flair_css_class" : "science",
"link_flair_text" : "",
"media" : null,
"media_embed" : { },
"name" : "t3_2a5vg8",
"num_comments" : 7331,
"num_reports" : null,
"over_18" : false,
"permalink" : "/r/IAmA/comments/2a5vg8/i_am_buzz_aldrin_engineer_american_astronaut_and/",
"saved" : false,
"score" : 4968,
"secure_media" : null,
"secure_media_embed" : { },
"selftext" : "I am hopi...
代码尝试
JSONObject response = new JSONObject(result);
JSONObject data = response.getJSONObject("data");
JSONArray hotTopics = data.getJSONArray("children");
for(int i=0; i<hotTopics.length(); i++) {
JSONObject topic = hotTopics.getJSONObject(i).getJSONObject("data");
DetailsData item = new DetailsData();
item.setAuthor(topic.getString("author"));
item.setPostTime(topic.getLong("created_utc"));
item.setScore(topic.getString("score"));
item.setComment(topic.getString("selftext"));
看似相同的JSON,它实际上适用于
{ "data" : { "after" : "t3_2a8ij0",
"before" : null,
"children" : [ { "data" : { "approved_by" : null,
"author" : "JiveMonkey",
"author_flair_css_class" : null,
"author_flair_text" : null,
"banned_by" : null,
"clicked" : false,
"created" : 1404948237.0,
"created_utc" : 1404919437.0,
"distinguished" : null,
"domain" : "i.imgur.com",
"downs" : 0,
"edited" : false,
"gilded" : 0,
"hidden" : false,
"id" : "2a8tuu",
"is_self" : false,
"likes" : null,
"link_flair_css_class" : null,
"link_flair_text" : null,
"media" : null,
"media_embed" : { },
"name" : "t3_2a8tuu",
"num_comments" : 1932,
"num_reports" : null,
"over_18" : false,
"permalink" : "/r/pics/comments/2a8tuu/norway_has_invented_a_bicycle_escalator/",
"saved" : false,
"score" : 4894,
"secure_media" : null,
"secure_media_embed" : { },
"selftext" : "",
"selftext_html" : null,
"stickied" : false,
"subreddit" : "pics",
"subreddit_id" : "t5_2qh0u",
"thumbnail" : "http://a.thumbs.redditmedia.com/nIstmQ8l1jl-UiU8.jpg",
"title" : "Norway has invented a bicycle escalator",
"ups" : 4894,
"url" : "http://i.imgur.com/ACr2e4h.jpg",
"visited" : false
},
"kind" : "t3"
},
答案 0 :(得分:0)
目标JSON是JSONArray
,其中“看似相同”的JSON是JSONObject
我想象一下,如果您查看抛出的JSONException
的堆栈跟踪,它会告诉您JSONArray
无法解析为JSONObject
要解析它,您可以将代码更改为以下内容:
JSONArray jArr = new JSONArray(result);
JSONObject response = jArr.getJSONObject(0); // grab the first object in the array