Android Parse JSON Array

2019-01-20 04:37发布

How Can I parse a JSON ARRAY to get the data without the [] and ""

here is the json

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

my code:

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

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

I just want the data. as:

23, Damansara - Puchong Hwy (Bandar Puchong Jaya), 47100 Puchong Batu Dua Belas, Selangor, Malaysia

Thanks

3条回答
叼着烟拽天下
2楼-- · 2019-01-20 04:50

Use JSONArray#join() to join the elements. Check out the JSONArray docs for more info.

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

It's unclear if the quotations are part of your input JSON string. If they show up in your join, you can easily remove them with the String#replace() method.

System.out.println(jsonArray.join(", ").replace("\"", ""));
查看更多
女痞
3楼-- · 2019-01-20 04:52

Try something like this:

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);
  }
查看更多
走好不送
4楼-- · 2019-01-20 05:00

Use JSONArray.join():

getJSONArray("formattedAddress").join(","));
查看更多
登录 后发表回答