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.
Learn to convert ArrayList to an array using toArray() method. The toArray() method returns an array that contains all elements from the list – in sequence (from first to last element in the list).
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.
JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.
If I read the JSONArray constructors correctly, you can build them from any Collection (arrayList is a subclass of Collection) like so:
ArrayList<String> list = new ArrayList<String>();
list.add("foo");
list.add("baar");
JSONArray jsArray = new JSONArray(list);
References:
Use Gson library to convert ArrayList to JsonArray.
Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();
As somebody figures out that the OP wants to convert custom List to org.json.JSONArray
not the com.google.gson.JsonArray
,the CORRECT answer should be like this:
Gson gson = new Gson();
String listString = gson.toJson(
targetList,
new TypeToken<ArrayList<targetListItem>>() {}.getType());
JSONArray jsonArray = new JSONArray(listString);
public void itemListToJsonConvert(ArrayList<HashMap<String, String>> list) {
JSONObject jResult = new JSONObject();// main object
JSONArray jArray = new JSONArray();// /ItemDetail jsonArray
for (int i = 0; i < list.size(); i++) {
JSONObject jGroup = new JSONObject();// /sub Object
try {
jGroup.put("ItemMasterID", list.get(i).get("ItemMasterID"));
jGroup.put("ID", list.get(i).get("id"));
jGroup.put("Name", list.get(i).get("name"));
jGroup.put("Category", list.get(i).get("category"));
jArray.put(jGroup);
// /itemDetail Name is JsonArray Name
jResult.put("itemDetail", jArray);
return jResult;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
With kotlin and Gson we can do it more easily:
implementation "com.squareup.retrofit2:converter-gson:2.3.0"
kotlin
file, add the following methodsimport com.google.gson.Gson import com.google.gson.reflect.TypeToken fun <T> Gson.convertToJsonString(t: T): String { return toJson(t).toString() } fun <T> Gson.convertToModel(jsonString: String, cls: Class<T>): T? { return try { fromJson(jsonString, cls) } catch (e: Exception) { null } } inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type)
Note: Do not add declare class, just add these methods, everything will work fine.
create a reference of gson:
val gson=Gson()
To convert array to json string, call:
val jsonString=gson.convertToJsonString(arrayList)
To get array from json string, call:
val arrayList=gson.fromJson<ArrayList<YourModelClassName>>(jsonString)
To convert a model to json string, call:
val jsonString=gson.convertToJsonString(model)
To convert json string to model, call:
val model=gson.convertToModel(jsonString, YourModelClassName::class.java)
Add to your gradle:
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
Convert ArrayList
to JsonArray
JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);
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