2015-01-21 131 views
2

我如何分析一個JSON數組來獲取數據,而[]和 「」的Android解析JSON陣列

這裏是JSON

"formattedAddress": [ 
"23, Damansara - Puchong Hwy (Bandar Puchong Jaya)", 
"47100 Puchong Batu Dua Belas, Selangor", 
"Malaysia" 
] 

我的代碼:

poi.setFormattedAddress(jsonArray.getJSONObject(i).getJSONObject("location").getJSONArray("formattedAddress").toString()); 

輸出: [「23,白沙羅 - 蒲種高速公路(蒲種高速公路)」,「47100 Puchong Batu Dua Belas,Selangor」,「馬來西亞」]

我只想要數據。如:

23,白沙羅 - 蒲種高速公路(新華社蒲種再也),47100個蒲種巴圖杜阿貝拉斯,馬來西亞雪蘭莪州

感謝

+1

可能是你的JSON數組是不正確的。請檢查此鏈接http://www.tutorialspoint.com/android/android_json_parser.htm – Pavya 2015-01-21 03:58:13

+0

是的,我認爲你的JSON是不正確的。 – eLemEnt 2015-01-21 04:03:34

+0

嘗試讀取數據作爲字符串數組。字符串[] – toidiu 2015-01-21 04:06:38

回答

1

使用JSONArray#join()加入元素。查看JSONArray文檔瞭解更多信息。

poi.setFormattedAddress(
    jsonArray.getJSONObject(i).getJSONObject("location") 
     .getJSONArray("formattedAddress").join(", ")); // passing ", " as the separator 

目前還不清楚引用是否是輸入JSON字符串的一部分。如果他們出現在您的加入中,您可以使用String#replace()方法輕鬆刪除它們。

System.out.println(jsonArray.join(", ").replace("\"", "")); 
+0

謝謝你的回覆。我試過。加入,這是輸出:「Northpoint Midvalley城市」,「吉隆坡,吉隆坡」,「馬來西亞」 – Joolah 2015-01-21 04:15:05

+0

對不起,我錯過了.join(「,」).replace(「\」「, 「」)); - 它現在可以工作 – Joolah 2015-01-21 04:17:33

+0

請刷新頁面,以便我的編輯顯示出來,使用replace(),如我的答案中所示 – 2015-01-21 04:17:34

0

嘗試是這樣的:

public String getFormattedAddressFromArray(JSONArray array) { 
    List<String> strings = new ArrayList<String>(); 
    try { 
     for (int i = 0; i < array.length(); i++) { 
     strings.add(array.getString(i)); 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return TextUtils.join(", ", strings); 
    } 
0

使用JSONArray.join():

getJSONArray("formattedAddress").join(","));