0
votes

i'm new at kotlin. I get this error when parsing json.

FATAL EXCEPTION: OkHttp Dispatcher

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $ at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)

then it's point out this line

val homeFeed = gson.fromJson(body, list::class.java)

My code:

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import java.io.IOException
import java.util.*

class MainActivity : AppCompatActivity() {

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

    okht()
}

fun okht(){
    val url = "https://jsonplaceholder.typicode.com/posts"
    val request = Request.Builder().url(url).build()
    val client = OkHttpClient()
    client.newCall(request).enqueue(object: Callback{

        override fun onResponse(call: Call, response: Response) {
            val body = response?.body()?.string()

           val gson = GsonBuilder().create()
           val homeFeed = gson.fromJson(body, list::class.java)
            println(homeFeed)
        }

        override fun onFailure(call: Call, e: IOException) {
            println("fail")
        }
    })
}
}

class list(val userId: Int, val id: Int, val title: String, val body: String)
1

1 Answers

0
votes

It's expecting a list object, but is finding a string. Check the response is what you're expecting.

Try: val listType = new TypeToken>(){}.getType() val homeFeed = new Gson().fromJson(jsonArray, listType)

Also, I recommend changing your list class to be called something more appropriate. And class names should begin with a capital letter.