Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
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"}

share|improve this question
add comment

5 Answers

up vote 0 down vote accepted

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");
}
share|improve this answer
add comment
// 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");
}
share|improve this answer
add comment

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.

share|improve this answer
add comment

You could try using a library like JsonPath.

Code would go something like this:

String rawJsonString = ...;
List<String> cities = JsonPath.read(rawJsonString, "$.city.name");
share|improve this answer
add comment

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");
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.