6

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?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Kartika Vij
  • 493
  • 2
  • 4
  • 18

5 Answers5

6

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)
Kalpesh Rupani
  • 991
  • 4
  • 12
6

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

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
3

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
}
Jigar Patel
  • 1,550
  • 2
  • 13
  • 29
1

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
}
Simson
  • 3,373
  • 2
  • 24
  • 38
1

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)