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?
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.
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.
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.
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.
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
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