2

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
  • 1
    may be your JSon array is not correct. please check this link tutorialspoint.com/android/android_json_parser.htm Commented Jan 21, 2015 at 3:58
  • Yeah I think your json is not correct.... Commented Jan 21, 2015 at 4:03
  • try reading the data as an array of Strings. String[] Commented Jan 21, 2015 at 4:06

3 Answers 3

1

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("\"", ""));
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your reply. I tried .join and this is the output: "Northpoint Midvalley City", "Kuala Lumpur, Kuala Lumpur", "Malaysia"
I am sorry, I missed the .join(", ").replace("\"", "")); - it now works
Please, refresh the page so that my edits show up. Use replace() as shown in my answer.
0

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);
  }

Comments

0

Use JSONArray.join():

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.