I want show information from API but I have this error:
Java.lang.Error: org.json.JSONException: Value okhttp3.internal.http.RealResponseBody@1e465c6 of type java.lang.String cannot be converted to JSONObject
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1173)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
Caused by: org.json.JSONException: Value okhttp3.internal.http.RealResponseBody@1e465c6 of type java.lang.String cannot be converted to JSONObject
package com.shayan.weatherapp
import android.nfc.Tag
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract.RawContacts
import android.util.Log
import android.widget.CheckBox
import okhttp3.*
import org.json.JSONObject
import java.io.IOException
class MainActivity : AppCompatActivity() {
var checkbox:CheckBox? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
checkbox = findViewById<CheckBox>(R.id.checkBox)
var client = OkHttpClient()
var request = Request.Builder().url("https://jsonplaceholder.typicode.com/todos/1")
.build()
client.newCall(request).enqueue(object:Callback{
override fun onFailure(call: Call, e: IOException) {
}
override fun onResponse(call: Call, response: Response) {
val rawContact = response.body!!.toString()
val jsonObject = JSONObject(rawContact)
val myTodo = Todo(
jsonObject.getInt("userId"),
jsonObject.getInt("id"),
jsonObject.getString("title"),
jsonObject.getBoolean("completed"))
runOnUiThread {
setValueForCheckBox(myTodo)
}
}
})
}
fun setValueForCheckBox(todo: Todo){
checkbox?.isChecked= todo.completed
checkbox?.text = todo.title
}
}```
You have to replace
val rawContact = response.body!!.toString()
with
val rawContact = response.body!!.string()
This is because the toString()
method returns a string representation of the ResponseBody
object that for complex objects might contain additional information like package name, address in memory etc. Instead, you're insterested in a string representation of the body response: for that string()
method is what you need.