0
JSONArray cities = json.getJSONArray("city");

With the above code got the following output:

{
"id":"1",
"name":"London"
"country":"United Kingdom"
},

{
"id":"2",
"name":"Madrid"
"country":"Spain"
},

{"id":"3",
"name":"Paris"
"country":"France"
},

{
"id":"3",
"name":"Zurich"
"country":"Switzerland"
}

How can I get only the name from the JSON array to a string array?

e.g.: String[] s ={"London","Madrid","Paris","Zurich"}

5 Answers 5

1
// you should probably mention what json library you use in your question
String[] cities = new String[cities.length()];
for (int i = 0; i<cities.length(); i++) {
    cities[i] = cities.getJsonObject(i).getString("name");
}
Sign up to request clarification or add additional context in comments.

Comments

1

cities is an array of JSONObjects. iterate through that array of JSONObjects, and get the "name" attribute from each. See @pb2q's answer where the code has been conveniently written for you.

Comments

0

Loop through the JSONArray and pull out the "name" fields. This is done similarly to your json.getJSONArray("city"); call, only in a loop:

JSONArray cities = json.getJSONArray("city");
JSONObject city = null;
String[] s = new String[cities.length()];

for (int i = 0; i < cities.length(); i++)
{
    city = cities.getJsonObject(i);
    s[i] = city.get("name");
}

Comments

0

You could try using a library like JsonPath.

Code would go something like this:

String rawJsonString = ...;
List<String> cities = JsonPath.read(rawJsonString, "$.city.name");

Comments

0

Use JsonPath http://code.google.com/p/json-path/

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>0.8.1</version>
</dependency>

you can get all city names

String rawJsonString = "...";
List<String> cities = JsonPath.read(rawJsonString, "$.city[*].name");

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.