I am trying to parse JSON with Kotlin. As I am a beginner in Kotlin, this is still a little bit difficult.
Here is my Json example :
"orders": {
"id" = 1;
"base_order": {
"id" = 1;
"price" = 10;
}
"picks": {
"0": {
"name": "Omelette du fromage"
}
"1": {
"name": "Baguette"
}
}
}
So here is how I am trying to parse that :
@Parcel
class Orders {
var id = 0L
var baseOrder = BaseOrder()
var picks = ArrayList<Picks>()
fun loadFromJson(json: JsonObject) {
id = readLong(json, TAG_ID)
json.get(TAG_BASE_ORDER)?.let {
if (it.isJsonObject)
baseOrder.loadFromJson(it.asJsonObject)
}
}
companion object {
private const val TAG_ID = "id"
private const val TAG_BASE_ORDER = "base_order"
}
}
Here is my BaseOrder class :
@Parcel
class BaseOrder {
var id = 0L
var price = 0f
fun loadFromJson(json: JsonObject) {
id = readLong(json, TAG_ID)
price = readFloat(json, TAG_PRICE)
}
companion object {
private const val TAG_ID = "id"
private const val TAG_PRICE = "price"
}
}
And finally my Picks class :
@Parcel
class Picks {
var name = ""
fun loadFromJson(json: JsonObject) {
name = readString(json, TAG_NAME)
}
companion object {
private const val TAG_NAME = "name"
}
}
I need to parse my "picks" list, ideally in my ArrayList of Picks() but I have no idea how to loop to parse that kind of list with "0", "1", "2"... index keys.
If you think I did not search enough, please give me at least the name of this kind of json list, so I can do better searches.
========================
EDIT :
I finally found out how to do it ! Here is my code :
@Parcel
class Orders {
var id = 0L
var baseOrder = BaseOrder()
var picks = ArrayList<Picks>()
var pickItem = Picks() // This is a buffer
fun loadFromJson(json: JsonObject) {
id = readLong(json, TAG_ID)
json.get(TAG_BASE_ORDER)?.let {
if (it.isJsonObject)
baseOrder.loadFromJson(it.asJsonObject)
}
// Here I am going to start parsing it :
json.get(TAG_PICKS)?.let {
if (it.isJsonObject)
it.asJsonObject.entrySet().forEach() {
it.value.let {
if (it.isJsonObject)
pickItem.loadFromJson(it.asJsonObject)//I parse the json item in the buffer
picks.add(pickItem) // I add the buffer into the array at the right place
pickItem = Picks() // I re-init the buffer for next loops
}
}
}
}
companion object {
private const val TAG_ID = "id"
private const val TAG_BASE_ORDER = "base_order"
}
}
It is a little bit dirty, as I am using a buffer and I think I could do without it, but the syntax is here.
As a very beginner in Kotlin, I am open to any suggestions.
Thanks for the people who tried to help me out :)