當我調用服務器時,它的響應基於json對象。其實,我知道如何解析JSON對象,但這個迴應對我來說很奇怪。服務器響應是:Android,解析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, 「時間」:1337861978000, 「新」:假的, 「機器」: 415106952,「inc」: - 2024241794},「body」:「Not Available!」,「title」:「波蘭vs希臘」,「publishedDate」:「2012-06-08 17:00:00 +0100」,「 clazz中 「:」 SoccerMatchPreview」, 「refKey」: 「類型org.json.JSONObject的SoccerMatchPreview_4fb897be18be8b87f9117595」}無法轉換至JSONArray
任何建議,將不勝感激。由於
謝謝親愛展的基礎上,我發現你所提到的是「ID」是錯誤的關鍵,因爲我並不需要它的項目。如何獲得body,publishedDate,refKey和title?基於什麼,我應該不得不解析「響應」字符串? – Hesam
要獲得publishedDate,refKey和title,您只需要JSONObject jObject = new JSONObject(response); String publishedDate = jObject.get(「publishedDate」);等等。 –
這部分,我強烈建議你看看一個好的JSON庫,從谷歌GSON似乎是一個很好的。這裏是一個簡短的教程:http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/ –