我尝试在 Kotlin 中使用 OKHttp 解析 JSON 字符串,但它给了我以下错误并且应用程序崩溃了:
2019-09-30 15:27:24.871 4808-4933/com.kabelash.kotlinrepo E/AndroidRuntime:致命异常:OkHttp 调度程序进程:com.kabelash.kotlinrepo,PID:4808 com.google.gson.JsonSyntaxException:java.lang .IllegalStateException:预期为 BEGIN_OBJECT,但在第 1 行第 2 列路径 $ 位于 com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226) 处为 BEGIN_ARRAY
我的 MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView_main.layoutManager = LinearLayoutManager(this);
fetchJson()
}
fun fetchJson() {
val url = "https://api.myurl.com/"
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()
println(body)
val gson = GsonBuilder().create()
val feed = gson.fromJson(body, Feed::class.java)
runOnUiThread {
recyclerView_main.adapter = MainAdapter(feed)
}
}
override fun onFailure(call: Call, e: IOException) {
println("Request Failed")
}
})
}
}
class Feed (val name: String, val created_at: String, val owner: Owner)
class Owner (val login: String, val avatar_url: String)
我在其中花了很多时间,但仍然无法弄清楚。我该如何解决呢?有什么建议么?
哆啦的时光机
繁星coding
相关分类