JSONArray to string array

2022-09-03 15:43:34

将json数组转换为字符串[]看起来太多的沸腾板。有没有更简单,更优雅的方法?

final JSONArray keyArray = input.getJSONArray("key");
String[] keyAttributes = new String[keyArray.length()];
for(int i = 0; i < keyArray.length(); i++) {
    keyAttributes[i] = keyArray.getString(i);
}

答案 1

使用 gson。它有一个比 更友好的 API。org.json

集合示例(来自用户指南):

Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);

//(Serialization)
String json = gson.toJson(ints); ==> json is [1,2,3,4,5]

//(Deserialization)
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);
//ints2 is same as ints

答案 2

你是对的!即使@Sean帕特里克·弗洛伊德(Patrick Floyd)的答案也太多了,无法将JSON数组隐藏为字符串[]或任何其他类型的数组类。相反,这是我发现的优雅之处:

JsonArray jsonArray = input.getAsJsonArray("key");

Gson gson = new Gson();
String[] output = gson.fromJson(jsonArray , String[].class)

注 1:对于上述示例,必须是字符串数组,不带任何属性名称。例如:JsonArray

{key:["Apple","Orange","Mango","Papaya","Guava"]}

注2:上面使用的类来自库,而不是来自库的类。JsonObjectcom.google.gsonJSONObjectorg.json