JSON字符串到java中的String数组

时间:2012-08-29 18:53:37

标签: java json

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

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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");
}

答案 2 :(得分: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");
}

答案 3 :(得分:0)

您可以尝试使用JsonPath等库。

代码会是这样的:

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

答案 4 :(得分: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");