white-imp
white-imp

Reputation: 323

Kotlin: get List object from JSON string

Exploring kotin possibilities at first time and a bit confused how to convert JSON string into List object.

data.json is quite simple

{
  "0" : "some picture",
  "1" : "other picture"
}

Trying to convert like this:

        val inputStream: InputStream = context?.assets?.open("data.json") ?: return null
    val size: Int = inputStream.available()
    val buffer = ByteArray(size)
    inputStream.read(buffer)
    val jsonString = String(buffer)

    println(jsonString)

    val gson = Gson()
    
    // THIS LINE CALLS ERROR
    val list: List<String> = gson.fromJson(jsonString, Array<String>::class.java).asList()

    list.forEachIndexed {index, item -> Log.i("item", "$index::$item")}

And getting error as result

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

How to fix this or how to correctly retrieve list object from json string?

Upvotes: 1

Views: 6545

Answers (2)

iknow
iknow

Reputation: 9862

This JSON isn't array. You have to make object fot this type. It will look like this:

import com.google.gson.annotations.SerializedName

data class JsonData(
    @SerializedName("0")
    val x0: String,
    @SerializedName("1")
    val x1: String
)

Now in Your activity You can convert json to obbject:

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val gson = Gson()

        val json =
            """
            {
                "0" : "some picture",
                "1" : "other picture"
            }
            """

        val jsonData = gson.fromJson<JsonData>(json, JsonData::class.java)

        println(jsonData.x0) // some picture
        println(jsonData.x1) // other picture
    }
}

Now You can operate on that obcject but if You want list of string You can do it like this:

val list = arrayListOf<String>(jsonData.x0, jsonData.x1)
println(list) //  [some picture, other picture]

Upvotes: 0

akhilesh0707
akhilesh0707

Reputation: 6899

Instead of using List

val list: List<String> = gson.fromJson(jsonString, Array<String>::class.java).asList()

Use Map (This will parse your json data into map)

val map = gson.fromJson<Map<String, String>>(jsonString, MutableMap::class.java)

Upvotes: 2

Related Questions