简体   繁体   中英

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?

If I read the JSONArray constructors correctly, you can build them from any Collection (arrayList is a subclass of Collection) like so:

val list = ArrayList<String?>()
list.add("jigar")
list.add("patel")
val jsArray = JSONArray(list)

You can also use GSON for read json see below example:

import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class userQuoteTravellers {
    @SerializedName("id")
    @Expose
    var id: Int? = null
    @SerializedName("quoteId")
    @Expose
    var quoteId: Int? = null
    @SerializedName("travellerId")
    @Expose
    var travellerId: Any? = null
}

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

With Dependencies

Add to your gradle:

implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

Convert ArrayList to JsonArray

val jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList)

Without Dependencies

val jsonElements = JSONArray(itemsArrayList)

try this: val userQuote = response.getJSONArray("userQuoteTravellers")

then call the data inside like this:

for (i in 0 until userQuote.length()) {
    val quotes = userQuote.getJSONObject(i)
    // then call the other data here
}

You can achieve this by using this

  implementation 'com.squareup.retrofit2:converter-gson:2.3.0'


  var gson = Gson()
  var jsonData = gson.toJson(PostPojo::class.java)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM