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?
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.
-
1Is arrays.asList necessary? Even tough JSONArray has no constructor with String[] as parameter the following code works fine for me:
String[] strings = {"a", "b"}; JSONArray json = new JSONArray(strings); System.out.println(json.toString());
– M-- Aug 24 '13 at 11:04 -
1Both ways work, but at least in Android, JSONArray(strings) isn't supported until API 19 – Caren Mar 31 '15 at 16:52
-
The way that works in the current version of java is: new JSONArray().addAll(Arrays.asList(mStringArray)) – Cody Jacques Aug 21 '17 at 18:27
-
No, "arrays.asList" is not necessary; otherwise, it becomes the original array in a new array of one single entry. – david m lee May 16 '18 at 23:52
-
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
-
6Yep! Doesn't seem to work on normal String arrays though as they are not part of the Collection ( developer.android.com/reference/java/util/Collection.html )? But if all else fails you can just run a for loop for that. – Klaus Mar 2 '11 at 11:26
-
-
asList()
does not seem to work as I am having this problem right now – limeandcoconut May 13 '14 at 15:34
you need external library
json-lib-2.2.2-jdk15.jar
List mybeanList = new ArrayList();
mybeanList.add("S");
mybeanList.add("b");
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google Gson is the best library http://code.google.com/p/google-gson/
example key = "Name" value = "Xavier" and the value depends on number of array you pass in
try
{
JSONArray jArry=new JSONArray();
for (int i=0;i<3;i++)
{
JSONObject jObjd=new JSONObject();
jObjd.put("key", value);
jObjd.put("key", value);
jArry.put(jObjd);
}
Log.e("Test", jArry.toString());
}
catch(JSONException ex)
{
}
For a simple java String
Array you should try
String arr_str [] = { "value1`", "value2", "value3" };
JSONArray arr_strJson = new JSONArray(Arrays.asList(arr_str));
System.out.println(arr_strJson.toString());
If you have an Generic ArrayList of type String like ArrayList<String>
. then you should try
ArrayList<String> obj_list = new ArrayList<>();
obj_list.add("value1");
obj_list.add("value2");
obj_list.add("value3");
JSONArray arr_strJson = new JSONArray(obj_list));
System.out.println(arr_strJson.toString());
This is the correct syntax:
String arlist1 [] = { "value1`", "value2", "value3" };
JSONArray jsonArray1 = new JSONArray(arlist1);