Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONArray to string array

Tags:

java

json

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);
}
like image 829
Fakrudeen Avatar asked Jan 24 '11 06:01

Fakrudeen


People also ask

Can we convert a JSONArray to string in Java?

int size = exampleList. size(); String[] stringArray = exampleList. toArray(new String[size]); This will convert our JSON array into a String array.

Can we convert JSON array to string?

Stringify a JavaScript ArrayUse the JavaScript function JSON. stringify() to convert it into a string.

Can a JSON file be an array?

JSON can be either an array or an object.

How get values from JSONArray?

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.


2 Answers

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
like image 111
Sean Patrick Floyd Avatar answered Oct 09 '22 23:10

Sean Patrick Floyd


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.

like image 21
fahmy Avatar answered Oct 09 '22 23:10

fahmy