JSONArray到字符串数组

Fak*_*een 15 java json

将json数组转换为string []看起来似乎太多boilterplate.有没有更简单优雅的方式?

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);
}
Run Code Online (Sandbox Code Playgroud)

Sea*_*oyd 7

使用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
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.int [] ints2 = gson.fromJson("[1,2,3,4,5]",int [] .class); 这样的事情就是我想要的. (2认同)