Reputation: 613
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?
Upvotes: 9
Views: 31084
Reputation: 29844
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 } ]
Upvotes: 6
Reputation:
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
}
Upvotes: 1
Reputation: 116
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)
Upvotes: 1
Reputation: 1568
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
}
Upvotes: 3
Reputation: 1049
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)
Upvotes: 6