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

使用上面的代码得到以下输出:

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

4

5 回答 5

1

cities是 JSONObjects 的数组。遍历该 JSONObjects 数组,并"name"从每个对象中获取属性。请参阅@pb2q 的答案,其中代码已为您方便地编写。

于 2012-08-29T19:03:02.103 回答
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");
}
于 2012-08-29T19:04:47.157 回答
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");
}
于 2012-08-29T19:05:20.630 回答
0

您可以尝试使用JsonPath 之类的库。

代码会是这样的:

String rawJsonString = ...;
List<String> cities = JsonPath.read(rawJsonString, "$.city.name");
于 2012-08-29T20:10:23.183 回答
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");
于 2013-03-15T18:47:35.163 回答