2016-09-08 125 views
-2

我可以访问条目数组而无需调用上层对象。请给我一个例子,我如何访问entries数组。 我对此很感兴趣,所以当JSON数据具有不同的条目和提取方法时,它非常混乱。我想我没有把握好查询。我明白数组[]和对象{}之间的区别,但我仍然在学习组合。 谢谢。使用对象调用数组。 (Android,JSON)

JSON:

{ 
    "responseData":{ 
     "feed":{ 
     "feedUrl":"", 
     "title":"", 
     "link":"", 
     "author":"", 
     "description":"", 
     "type":"", 
     "entries":[ 
      { 
       "title":"", 
       "link":"", 
       "author":"", 
       "publishedDate":"", 
       "contentSnippet":"", 
       "content":"", 
       "categories":[ 
        "" 
       ] 
      }, 
      { 
       "title":"", 
       "link":"", 
       "author":"", 
       "description":"", 
       "type":"", 
       "entries":[ 
        { 
        "title":"", 
        "link":"", 
        "author":"", 
        "publishedDate":"", 
        "contentSnippet":"", 
        "content":"", 
        "categories":[ 
         "" 
        ] 
        } 
       ] 
      } 
     }, 
     "responseDetails":null, 
     "responseStatus":200 
     } 

代码:

HttpEntity entity = response.getEntity(); 
String data = EntityUtils.toString(entity); 
JSONObject jsono = new JSONObject(data); 
JSONArray jarray = jsono.getJSONArray("entries"); 
NewsList.content = (int)jarray.length(); 
for (int i = 0; i < jarray.length(); i++) { 
    JSONObject object = jarray.getJSONObject(i); 
    NewsList News = new NewsList(); 
    News.setId(object.getString("title")); 
    News.setName(object.getString("publishedDate")); 
    News.setAuthor(object.getString("link")); 
    NewsListList.add(News); 
} 
+0

您在此处提供的Json格式不正确。请用正确的更新它。 – dhuma1981

+0

是的,你可以轻松地使用GSON来做到这一点。 –

+0

你的json是错的 – Nikhil

回答

0

号,而不必调用上对象,则不能获得条目阵列。

你可以解析上面的json响应。

JSONObject jsono = new JSONObject(data); 
JSONObject json1 = jsono.getJSONObject("responseData"); 
JSONObject json2 = json1.getJSONObject("feed"); 
String feedUrl = json2.getString("feedUrl"); 
JSONArray jarray = json2.getJSONArray("entries"); 
NewsList.content = (int)jarray.length(); 
for (int i = 0; i < jarray.length(); i++) { 
JSONObject object = jarray.getJSONObject(i); 
NewsList News = new NewsList(); 
News.setId(object.getString("title")); 
News.setName(object.getString("publishedDate")); 
News.setAuthor(object.getString("link")); 
NewsListList.add(News); 
} 

希望这会对你有所帮助。

+0

干杯。很好解释和直截了当。 – jaroman777