Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ArrayList to JSONArray() in Kotlin

I have a list in my POJO class:

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

I want to pass this list as it is in JSONArray and passing it as:

JSONArray.put(list)

It is being sent as:

"userQuoteTravellers": [ "[]" ]

But I want to send it as

"userQuoteTravellers": []

How can I achieve this in Kotlin without using any loop?

like image 807
Kartika Vij Avatar asked May 14 '26 14:05

Kartika Vij


1 Answers

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 } ]

like image 115
Willi Mentzel Avatar answered May 16 '26 02:05

Willi Mentzel