从JSON对象解析字符串数组

问题描述:

这可能太简单了,但我只是无法找到解决方案.如何直接从JSON对象中解析string array?

It might be too easy but I just cannot find a solution to this. How can I directly parse the string array out of the JSON object?

例如,

json = {"names":["John", "Alex", "David"]}

我无法执行json.getJSONArray("names"),因为它没有返回string array.

I cannot do json.getJSONArray("names") since it doesn't return a string array.

您可以将数据作为json数组并通过其循环以创建列表

You can get the data as a json array and the loop through it to create a list

JSONObject jsonObject = new JSONObject("{names:['1','2','3']}");
JSONArray jsonArray = jsonObject.getJSONArray("names");

List<String> names = new ArrayList<String>();
for(int i = 0; i < jsonArray.length(); i++){
     names.add(jsonArray.getString(i));
}
System.out.println(names);