Take the tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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);
}
share|improve this question
1  
Assuming org.json.JSONArray. Nope, that's as good as it gets. –  Dean Povey Jan 24 '11 at 6:59
add comment

3 Answers

up vote 3 down vote accepted

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
share|improve this answer
1  
Thanks. int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); something like this is what I was looking for. –  Fakrudeen Jan 24 '11 at 10:01
add comment

It's ugly but believe it or not this works:

String[] keyAttributes = keyArray.toString.substring(1,keyArray.toString.length-1).replaceAll("\"","").split(",")
share|improve this answer
add comment

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

share|improve this answer
 
Even using a 'well known' library would do for me. –  Fakrudeen Jan 24 '11 at 7:07
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.