本文介绍了致命异常:OkHttp Dispatcher,应为Begin_ARRAY,但在第1行第1列路径处为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从Coinmarket API获取前10枚硬币。突出显示了以下代码中出现错误的部分。我不明白为什么它会导致我的应用程序崩溃。请帮帮忙!
private fun loadFirst10Coin(){
client = OkHttpClient()
request = Request.Builder()
.url(String.format("https://api.coinmarketcap.com/v1/ticker/?start=0&limit=10"))
.build()
client.newCall(request)
.enqueue(object: Callback
{
override fun onFailure(call: Call, e: IOException) {
Log.d("Error", e.toString())
}
override fun onResponse(call: Call, response: Response) {
val body = response?.body!!.string()
val gson = Gson()
//This line is giving me error//
**items = gson.fromJson(body, object: TypeToken<List<CoinModel>>() {}.type)**
runOnUiThread{
adapter.updateData(items)
}
}
})
}
这是我的Logcat的外观
2022-01-27 16:14:01.224 22322-14470/com.example.cryptocheck E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.example.cryptocheck, PID: 22322
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
at com.google.gson.Gson.fromJson(Gson.java:975)
at com.google.gson.Gson.fromJson(Gson.java:928)
at com.google.gson.Gson.fromJson(Gson.java:877)
at com.example.cryptocheck.MainActivity$loadFirst10Coin$1.onResponse(MainActivity.kt:81)
at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:349)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:80)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at com.google.gson.Gson.fromJson(Gson.java:963)
推荐答案
您收到的错误是因为字符串不是从";[";开始。
友好提示:您不应该再使用GSON。项目维护人员之一杰克·沃顿建议使用Moshi、Jackson或kotlinx.Serialization。这篇关于致命异常:OkHttp Dispatcher,应为Begin_ARRAY,但在第1行第1列路径处为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!