2012-08-29 105 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");