15

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);
}
1
  • 1
    Assuming org.json.JSONArray. Nope, that's as good as it gets. Commented Jan 24, 2011 at 6:59

4 Answers 4

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); something like this is what I was looking for.
2

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.

Comments

0

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

1 Comment

Even using a 'well known' library would do for me.
0
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;
};

1 Comment

person asking the question wants to avoid this and has posted exact same snippet in question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.