我试图在 Kotlin 中使用 OKHttp 解析 JSON 字符串,但它给了我以下错误并且应用程序崩溃了:
2019 年 9 月 30 日 15:27:24.871 4808-4933/com.kabelash.kotlinrepo E/AndroidRuntime:致命异常:OkHttp 调度程序进程:com.kabelash.kotlinrepo,PID:4808 com.google.gyntaxException:java .IllegalStateException:预期为 BEGIN_OBJECT,但在第 1 行第 2 列路径 $ 处为 BEGIN_ARRAY,位于 com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
我的主活动.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)
我的 MainAdapter.kt
class MainAdapter(val feed: Feed): RecyclerView.Adapter<CustomViewHolder>(){
override fun getItemCount(): Int {
return feed.name.count()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val rowCell = layoutInflater.inflate(R.layout.repo_row, parent, false)
return CustomViewHolder(rowCell)
}
override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
val fd = feed.name.get(position)
holder.view.titleText.text = fd.toString()
}
}
class CustomViewHolder(val view: View): RecyclerView.ViewHolder(view) {
}
我花了很多时间在里面,但我仍然无法弄清楚。我该如何解决?有什么建议么?
API 返回一组 Json 对象。因此,您需要将其解析为数组。
而不是val feed = gson.fromJson(body, Feed::class.java)
你应该把val feed = gson.fromJson(body, Array<Feed>::class.java)
主适配器
class MainAdapter(val feed: Array<Feed>): RecyclerView.Adapter<CustomViewHolder>(){
override fun getItemCount(): Int {
return feed.count()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val rowCell = layoutInflater.inflate(R.layout.repo_row, parent, false)
return CustomViewHolder(rowCell)
}
override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
val fd = feed.get(position)
holder.view.titleText.text = fd.name.toString()
}
}
class CustomViewHolder(val view: View): RecyclerView.ViewHolder(view) {
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句