Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert normal Java Array or ArrayList to Json Array in android

Tags:

java

json

android

Is there any way to convert a normal Java array or ArrayList to a Json Array in Android to pass the JSON object to a webservice?

like image 816
jennifer Avatar asked Mar 02 '11 11:03

jennifer


People also ask

How can we convert a list to the JSON array in Java?

We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.

Can you convert array to JSON?

You convert the whole array to JSON as one object by calling JSON. stringify() on the array, which results in a single JSON string. To convert back to an array from JSON, you'd call JSON. parse() on the string, leaving you with the original array.

Can we convert JSONArray to JSONObject?

We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.


2 Answers

If you want or need to work with a Java array then you can always use the java.util.Arrays utility classes' static asList() method to convert your array to a List.

Something along those lines should work.

String mStringArray[] = { "String1", "String2" };  JSONArray mJSONArray = new JSONArray(Arrays.asList(mStringArray)); 

Beware that code is written offhand so consider it pseudo-code.

like image 163
Octavian A. Damiean Avatar answered Oct 05 '22 09:10

Octavian A. Damiean


ArrayList<String> list = new ArrayList<String>(); list.add("blah"); list.add("bleh"); JSONArray jsArray = new JSONArray(list); 

This is only an example using a string arraylist

like image 20
Reno Avatar answered Oct 05 '22 09:10

Reno