1

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?

1
  • 1
    The error is telling you what you need to know. You are telling Gson to expect an array (would be an array if enclosed in [ ] ) but your string is an object (enclosed in { } ) Commented Sep 22, 2020 at 16:18

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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]

4 Comments

what if he has more data in json like "2": "Some more data", "2": "Some more data2"
Then it won't work but I assumed that JSON only contains these two values. But if it really has many values this JSON should be just an array of string
Thanks for reply. There could be more than two values, that's just an example.
Ohh, okay, so use the @akhilesh0707 answer, it should work well. But If it is Your JSON and every first value is just an index I think that You should make an array like this: [ "some picture", "other picture" ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.