put adds the list as an element to the JSONArray. Thats not what you want. You want your JSONArray to represent the list.

JSONArray offers a constructor for that:

val jsonArray = JSONArray(listOf(1, 2, 3))

But there is a much easier way. You don't need to worry about single properties. Just pass the whole POJO.

Let's say you have this:

class QuoteData(val id: Int, val quoteId: Int, travellerId: Int?)
class TravelerData(val userQuoteTravellers: List<QuoteData>)

val travelerData = TravelerData(listOf(QuoteData(1354, 546, null)))

You just have to pass travelerData to the JSONArray constructor:

val travelerDataJson = JSONArray(travelerData)

and it will be represented like this:

"userQuoteTravellers": [ { "id": 1354, "quoteId": 526, "travellerId": null } ]

Answer from Willi Mentzel on Stack Overflow
Discussions

android - How to add ArrayList to JsonObject in Kotlin - Stack Overflow
PaymentDetails class data class PaymentDetails( val type:String, val bank: String, val branch: String, val account_no: String, val cheque_date:String, val return_type:Boolean, val cheque_no:String... More on stackoverflow.com
๐ŸŒ stackoverflow.com
December 4, 2018
how to parse JSONArray to List<CustomObject> ?
I'm trying without success to serialize JSONArray to local variable List of CustomObjects, when CustomObject class is Serializable, i reread all the q&a, all the documents, I can not unders... More on github.com
๐ŸŒ github.com
14
July 22, 2018
android - Converting JSONarray to ArrayList - Stack Overflow
I am downloading a JSON string and converting it to JSONArray. Im putting it into a listview and need to be able to delete from that listview later, and since JSONArray has no .remove method (Thanks More on stackoverflow.com
๐ŸŒ stackoverflow.com
android - Can't convert JSONArray into a list (Kotlin) - Stack Overflow
Communities for your favorite technologies. Explore all Collectives ยท Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Kotlin
kotlinlang.org โ€บ api โ€บ kotlinx.serialization โ€บ kotlinx-serialization-json โ€บ kotlinx.serialization.json โ€บ -json-array
JsonArray | kotlinx.serialization โ€“ Kotlin Programming Language
Class representing JSON array, consisting of indexed values, where value is arbitrary JsonElement ยท Since this class also implements List interface, you can use traditional methods like List.get or List.getOrNull to obtain Json elements
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ how-to-convert-arraylist-to-jsonarray-in-kotlin
Android: Converting ArrayList to JSONArray() using Kotlin
May 7, 2023 - ... You have initialized a jsonObject ... converting ArrayList to JSON and post to a url, You could try something like that: 1) Build the JSON object ArrayList<Beacon> arrayL = new ArrayList<>(); JSONArray mJSONArray = new...
๐ŸŒ
Android Developers
developer.android.com โ€บ api reference โ€บ jsonarray
JSONArray | API reference | Android Developers
Skip to main content ยท English ยท Deutsch ยท Espaรฑol โ€“ Amรฉrica Latina ยท Franรงais ยท Indonesia ยท Polski ยท Portuguรชs โ€“ Brasil ยท Tiรชฬng Viรชฬฃt ยท ไธญๆ–‡ โ€“ ็ฎ€ไฝ“
๐ŸŒ
GitHub
github.com โ€บ Kotlin โ€บ kotlinx.serialization โ€บ issues โ€บ 179
how to parse JSONArray to List<CustomObject> ? ยท Issue #179 ยท Kotlin/kotlinx.serialization
July 22, 2018 - I'm trying without success to serialize JSONArray to local variable List of CustomObjects, when CustomObject class is Serializable, i reread all the q&a, all the documents, I can not unders...
Author ย  xdma
Top answer
1 of 16
204
ArrayList<String> listdata = new ArrayList<String>();     
JSONArray jArray = (JSONArray)jsonObject; 
if (jArray != null) { 
   for (int i=0;i<jArray.length();i++){ 
    listdata.add(jArray.getString(i));
   } 
} 
2 of 16
85

I've done it using Gson (by Google).

Add the following line to your module's build.gradle:

dependencies {
  // ...
  // Note that `compile` will be deprecated. Use `implementation` instead.
  // See https://stackoverflow.com/a/44409111 for more info
  implementation 'com.google.code.gson:gson:2.8.2'
}

JSON string:

private String jsonString = "[\n" +
            "        {\n" +
            "                \"id\": \"c200\",\n" +
            "                \"name\": \"Ravi Tamada\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c201\",\n" +
            "                \"name\": \"Johnny Depp\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c202\",\n" +
            "                \"name\": \"Leonardo Dicaprio\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c203\",\n" +
            "                \"name\": \"John Wayne\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c204\",\n" +
            "                \"name\": \"Angelina Jolie\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"female\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c205\",\n" +
            "                \"name\": \"Dido\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"female\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c206\",\n" +
            "                \"name\": \"Adele\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"female\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c207\",\n" +
            "                \"name\": \"Hugh Jackman\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c208\",\n" +
            "                \"name\": \"Will Smith\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c209\",\n" +
            "                \"name\": \"Clint Eastwood\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c2010\",\n" +
            "                \"name\": \"Barack Obama\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c2011\",\n" +
            "                \"name\": \"Kate Winslet\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"female\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        },\n" +
            "        {\n" +
            "                \"id\": \"c2012\",\n" +
            "                \"name\": \"Eminem\",\n" +
            "                \"email\": \"[email protected]\",\n" +
            "                \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
            "                \"gender\" : \"male\",\n" +
            "                \"phone\": {\n" +
            "                    \"mobile\": \"+91 0000000000\",\n" +
            "                    \"home\": \"00 000000\",\n" +
            "                    \"office\": \"00 000000\"\n" +
            "                }\n" +
            "        }\n" +
            "    ]";

ContactModel.java:

public class ContactModel {
     public String id;
     public String name;
     public String email;
}

Code for converting a JSON string to ArrayList<Model>:

Note: You have to import java.lang.reflect.Type;:

// Top of file
import java.lang.reflect.Type;

// ...

private void parseJSON() {
    Gson gson = new Gson();
    Type type = new TypeToken<List<ContactModel>>(){}.getType();
    List<ContactModel> contactList = gson.fromJson(jsonString, type);
    for (ContactModel contact : contactList){
        Log.i("Contact Details", contact.id + "-" + contact.name + "-" + contact.email);
    }
}

Hope this will help you.

Find elsewhere
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ kotlin โ€บ kotlin collections โ€บ parsing json arrays in kotlin with gson
Parsing JSON Arrays in Kotlin with Gson | Baeldung on Kotlin
March 19, 2024 - In this tutorial, weโ€™ll explore how to serialize and deserialize JSON arrays with Kotlin using Gson. In the context of Google Gson, serialization is a mechanism for converting the state of an object into a JSON representation.
๐ŸŒ
Kotlin Discussions
discuss.kotlinlang.org โ€บ javascript
Arraylist from json can not be iterated - JavaScript
August 12, 2017 - i created a ArrayList with PersonDto objects and transform it to a json string on the server to send it to the client. in the client i try to parse this string back to the ArrayList of PersonDto objects but only get an Array back val listPerson = JSON.parse (data...
๐ŸŒ
Codexpedia
codexpedia.com โ€บ home โ€บ kotlin โ€บ kotlin converting jsonarray to arraylist with extension functions
Kotlin converting JSONArray to ArrayList with extension functions - Codexpedia
March 24, 2022 - Convert string list from JSONArray to ArrayList fun JSONArray.toArrayList(): ArrayList { val list = arrayListOf() for (i in 0 until this.length()) { list.add(this.getString(i)) } return list } val messages = JSONArray("['aaa','bbb','ccc']") messages.toArrayList() Remove a string from JSONArray ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 52486898 โ€บ transforming-a-jsonobject-to-jsonarray-in-kotlin
arrays - Transforming a JSONObject to JSONArray in Kotlin - Stack Overflow
Kotlin code private fun loadRecyclerViewData() { val request = Request.Builder().url(URL_Json).build() val client = OkHttpClient() client.newCall(request).enqueue(object: Callback{ ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-convert-arraylist-to-string-using-gson
How to convert ArrayList to String using GSON?
package com.example.andy.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView result = findViewById(R.id.result); ArrayList<String> list = new ArrayList<String>(); list.add("JAVA"); list.add("Android"); list.add("Kotlin"); list.add("C programing Language"); list.add("C plus plus"); Gson gson = new Gson(); String arrayData = gson.toJson(list); result.setText(arrayData); } }
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-iterate-a-json-array-in-android-using-kotlin
How to iterate a JSON Array in Android using Kotlin?
{ super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" textView = findViewById(R.id.textView) val data = StringBuilder() val jsonObject = JSONObject(strJson) val jsonArray = jsonObject.optJSONArray("Employee") for (i in 0 until jsonArray.length()) { val jsonObject = jsonArray.getJSONObject(i) val id = jsonObject.optString("ID").toInt() val name = jsonObject.optString("Name") val salary = jsonObject.optString("Salary").toFloat() data.append("Employee ").append(i).append(" : ID= ") .append(id).append(" " + "Name= ") .append(name).append(" Salary= ") .append(salary).append(" ") } textView.text = data.toString() } }
Top answer
1 of 2
1

It's an ugly request, and you might be able to resolve it with an ugly solution :)

I wouldn't suggest this for anything serious, large, or anything that requires some hard and complex maintenance, but if this object will stay that simple (one int and two strings, non-nullable fields) and won't change a lot, you can do it manually:

class RailPoint(
    var railPointId: Int,
    var startTime: String,
    var endTime: String
)

val rails = listOf(
    RailPoint(1, "", "2021-10-19 07:37:19"),
    RailPoint(2, "2021-10-19 07:33:37", "2021-10-19 07:35:20"),
)

fun toJson(rails: List<RailPoint>): String {
    val sb = StringBuilder()
    
    rails.forEachIndexed { index, railPoint ->
        sb.append("\"railPoint[$index][railPointId]\": ${railPoint.railPointId},")
        sb.append("\"railPoint[$index][startTime]\": \"${railPoint.startTime}\",")
        sb.append("\"railPoint[$index][endTime]\": \"${railPoint.endTime}\",")
    }

    return "{ $sb }"
}

It is very dirty approach, but might be enough, as long as you don't make RailPoint more complex, especially, if you don't add members that are custom classes or collections.

(I assumed that times are Strings, but if they are not, just add some date formatting in the formula)

2 of 2
1

This can be solved by first having Gson serialize the list to a JsonArray, then combining the elements in a new JsonObject and afterwards serializing that object to JSON:

val rails: List<RailPoint> = ...

val gson = Gson()
val railsJsonList = gson.toJsonTree(rails).asJsonArray!!
val railsJsonObject = JsonObject()
// Transform elements
for (i in 0 until railsJsonList.size()) {
    val railPointJson = railsJsonList[i].asJsonObject

    for ((name, value) in railPointJson.entrySet()) {
        railsJsonObject.add("railPoint[$i][$name]", value)
    }
}
println(gson.toJson(railsJsonObject))
๐ŸŒ
Reddit
reddit.com โ€บ r/androiddev โ€บ how do i save an arraylist with json?
r/androiddev on Reddit: How do I save an ArrayList<(Custom object here)> with JSON?
May 14, 2014 -
public class Semester {    
private static final String JSON_ID = "id";
private static final String JSON_TITLE = "title";
private static final String JSON_CREDITS = "credits";
private static final String JSON_GPA = "gpa";
private static final String JSON_CUMULATIVECREDITS = "cumulativecredits";
private static final String JSON_CUMULATIVEGPA = "cumulativegpa";
private static final String JSON_COURSES = "courses";

private UUID id;
private String title;
private int credits;
private double GPA;
private int cumulativeCredits;
private double cumulativeGPA;

private ArrayList<Course> courses;

public Semester() {
    id = UUID.randomUUID();
    courses = new ArrayList<Course>();
    for (int i = 0; i < 6; i++) {
        courses.add(new Course());
    }
}

public Semester(JSONObject json) throws JSONException {
    id = UUID.fromString(json.getString(JSON_ID));
    title = json.getString(JSON_TITLE);
    credits = json.getInt(JSON_CREDITS);
    GPA = json.getDouble(JSON_GPA);
    cumulativeCredits = json.getInt(JSON_CUMULATIVECREDITS);
    cumulativeGPA = json.getDouble(JSON_CUMULATIVEGPA);

//what do i put here?

}

public JSONObject toJSON() throws JSONException {
    JSONObject json = new JSONObject();
    json.put(JSON_ID, id.toString());
    json.put(JSON_TITLE, title);
    json.put(JSON_CREDITS, credits);
    json.put(JSON_GPA, GPA);
    json.put(JSON_CUMULATIVECREDITS, cumulativeCredits);
    json.put(JSON_CUMULATIVEGPA, cumulativeGPA);

JSONArray array = new JSONArray(courses);

json.put(JSON_COURSES, array);

    return json;
}

.........

This is followed by a bunch of getters and setters for each private variable.

  • The first bolded item is the private ArrayList of a custom class that I made.

  • The second bolded item is what I need help with: how to retrieve the custom ArrayList just like the other variables.

  • Lastly, the third bolded item is my current idea of how to put an ArrayList into a JSONObject, but I don't know how to retrieve it. If there is another way, please tell me. Thank you.

๐ŸŒ
Java Guides
javaguides.net โ€บ 2019 โ€บ 07 โ€บ convert-list-to-json-array-using-jackson.html
Convert List to JSON Array Using Jackson
July 21, 2019 - package net.javaguides.jackson; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; /** * Using Jackson API for list serialization and deserialization * @author ramesh fadatare * */ public class JacksonListToJson { public static void main(String[] args) throws JsonProcessingException { // Create ObjectMapper object.