开发者

JSONArray to string array

It looks like too much boilterplate to convert a json array to string[]. Is there any simpler and elegant way?

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);
}


Use gson. It's got a much friendlier API than org.json.

Collections Examples (from the User Guide):

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


You are right! Even @Sean Patrick Floyd's answer is too much boilterplate to covert a JSON array to string[] or any other type of array class. Rather here is what I find to be elegant:

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

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

NOTE 1: JsonArray must be an array of strings, for the above example, without any property names. Eg:

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

Note 2: JsonObject class used above is from com.google.gson library and not the JSONObject class from org.json library.


There is no any built-in method that do this and I think it is the simplest way

Here is similar topic that will help you


public String[] jsonArrayToStringArray(JSONArray jsonArray) {
    int arraySize = jsonArray.size();
    String[] stringArray = new String[arraySize];

    for(int i=0; i<arraySize; i++) {
        stringArray[i] = (String) jsonArray.get(i);
    }

    return stringArray;
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜