2012-08-29 23 views
0
JSONArray cities = json.getJSONArray("city"); 

一个String数组与上面的代码得到了以下的输出:JSON字符串在Java

{ 
"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" 
} 

如何从JSON数组只得到名称到字符串数组?

例如为:String[] s ={"London","Madrid","Paris","Zurich"}

回答

0

循环通过JSONArray并拉出"name"字段。这同样做你的json.getJSONArray("city");电话,只在一个循环:

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

cities是一个JSONObjects阵列。遍历该JSONObjects数组,并获取各自的"name"属性。请参阅@ pb2q的答案,代码已经方便地为您编写。

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

你可以尝试使用库像JsonPath

代码会去是这样的:

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

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

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

你可以得到所有的城市名

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