[英]how to parse complicated json in android
我一直在關注一個教程,最后終於對AsyncTask有了相當的了解,以及如何發送http get請求以獲取返回的json。 我可以成功獲取json,但無法解析它。
我正在看的教程使用了一個非常簡單的天氣API,該API發送回非常容易的json以進行解析。
我的是一個包含有關每個項目的信息的搜索結果。 我的json看起來像這樣:
我意識到json對象和信息數組之間的區別。 關於如何解析以獲取有關每種啤酒的信息以及啤酒廠信息的信息,有些困惑。
我的代碼如下:
String jsonUrl = url + query;
Toast.makeText(this, jsonUrl, Toast.LENGTH_SHORT).show();
//todo: get json
new ReadJSONResult().execute(jsonUrl);
return false;
}
private class ReadJSONResult extends AsyncTask
<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
try {
///code below is what I kow I need to reconstruct and change to parse
JSONObject jsonObject = new JSONObject(result);
JSONObject weatherObservationItems =
new JSONObject(jsonObject.getString("weatherObservation"));
Toast.makeText(getBaseContext(),
weatherObservationItems.getString("clouds") +
" - " + weatherObservationItems.getString("stationName"),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
}
}
您還應該使用JSON解串器庫來支持嵌套對象的對象。 我建議Gson https://code.google.com/p/google-gson/
JSON響應中有一個Java類生成器。 jsongen.byingtondesign.com將解析您的json響應,並為您提供Java Bean類。 這將幫助您了解需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.