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);
}
int size = exampleList. size(); String[] stringArray = exampleList. toArray(new String[size]); This will convert our JSON array into a String array.
Stringify a JavaScript ArrayUse the JavaScript function JSON. stringify() to convert it into a string.
JSON can be either an array or an object.
You can get the value using the line: String value = (String) getKey(array, "key1") . We cast to a string because we know "key1" refers to a string object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With