我有這樣的JSON結果http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=25&q=http://www.abc.net.au/news/feed/51120/rss.xmlAndroid的JSON訪問縮略圖要素
我試圖訪問縮略圖位於條目> mediaGroups>內容>縮略圖> URL
但是我不確定如何各新聞文章訪問元素中的深層。這是我的代碼到目前爲止。
public List<NewsObj> constructJSON(String jsonIN){
ArrayList<NewsObj> newsList = new ArrayList<>();
try{
//add more levels to extract json
JSONObject jsonObject1 = new JSONObject(jsonIN);
String responseData = jsonObject1.getString("responseData");
Log.d("RECEIVEJSONOBJECTLEVEL1",responseData);
JSONObject jsonObject2 = new JSONObject(responseData);
String feed = jsonObject2.getString("feed");
Log.d("RECEIVEJSONOBJECTLEVEL2",feed);
JSONObject jsonObject3 = new JSONObject(feed);
String entries = jsonObject3.getString("entries");
Log.d("RECEIVEJSONOBJECTLEVEL3", entries);
JSONArray jsonArray1 = new JSONArray(entries);
for(int i=0; i<jsonArray1.length();i++){
JSONObject mediaGroups = jsonArray1.getJSONObject(i);
String mediaItems = mediaGroups.getString("mediaGroups");
String title = mediaGroups.getString("title");
String url = mediaGroups.getString("link");
String description = mediaGroups.getString("contentSnippet");
String publishedDate = mediaGroups.getString("publishedDate");
// main information for news article
//for further thumbnail sizes?
JSONArray jsonArray2 = new JSONArray(mediaItems);
for(int j=0;j<jsonArray2.length();j++){
JSONObject contents = jsonArray2.getJSONObject(j);
String contentItems = contents.getString("contents");
Log.d("RECEIVEJSONOBJECTARRAY2",contentItems);
JSONArray jsonArray3 = new JSONArray(contentItems);
for(int k=0;k<jsonArray3.length();k++){
JSONObject items = jsonArray3.getJSONObject(k);
//too specific
String imgurl = items.getString("url");
//Log.d("RECEIVEJSONOBJECTARRAY3",imgurl);
NewsObj aObj = new NewsObj(title, imgurl,url, publishedDate);
newsList.add(aObj);
}
}
}
}catch (JSONException e){
e.printStackTrace();
Log.d("RECEIVEJSONERROR",e.toString());
}
return newsList;
}
你會不斷得到關於如何,如果你繼續問同樣的問題:)解析JSON鏈接如果你想要一個簡單的解決方案,可以考慮使用GSON(和改造,如果你願意)。並使用此網站創建一些Java類http://www.jsonschema2pojo.org –
謝謝,Gson或翻新會更簡單嗎? – JianYA
Retrofit將REST API轉化爲基本的Java方法(它具有較高的學習曲線),而Gson則用於將JSON字符串反序列化爲Java對象,而無需手動遍歷和解析自己。這聽起來更簡單 –