Reputation: 3
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"}
Upvotes: 0
Views: 191
Reputation: 1909
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");
Upvotes: 0
Reputation: 40903
You could try using a library like JsonPath.
Code would go something like this:
String rawJsonString = ...;
List<String> cities = JsonPath.read(rawJsonString, "$.city.name");
Upvotes: 0
Reputation: 53694
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.
Upvotes: 1
Reputation: 59677
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");
}
Upvotes: 0
Reputation: 3095
// 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");
}
Upvotes: 1