jenik2205
jenik2205

Reputation: 475

Parse JSON using GSON in Kotlin

I have JSON data like this and I want to parse using GSON in Kotlin

{"items":["Green Tea","19,90"]}

First item is name of product, second is price of product.

I am not really sure how to do it. Json format is correct. Do I have to create data class? How it should look like?

Upvotes: 1

Views: 268

Answers (2)

jenik2205
jenik2205

Reputation: 475

After Giorgi answer and some research I have result:

class Items(val items: List<String>)
val gson = GsonBuilder().create()
val getItem = gson.fromJson(body, Items::class.java)
val result = getItem.items

runOnUiThread {
    textView.append(result[0].toString() + " " + result[1].toString())
              }

Upvotes: 1

Giorgi Anakidze
Giorgi Anakidze

Reputation: 216

You'll have to make two data classes like

data class MainItem(val items: List<ItemsDataClass>)

data class ItemsDataClass(val name: String, val price: String)

And after that parse MainItem from your JSON.

Upvotes: 1

Related Questions