[我试图在Kotlin中使用OKHttp解析JSON字符串,但它给了我以下错误,并且应用程序崩溃了:
2019-09-30 15:27:24.871 4808-4933 / com.kabelash.kotlinrepo E / AndroidRuntime:致命例外:OkHttp Dispatcher流程:com.kabelash.kotlinrepo,PID:4808com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期为BEGIN_OBJECT,但在第1行第2列路径处为BEGIN_ARRAY在com.google.gson.internal.bind.ReflectiveTypeAdapterFactory $ Adapter.read(ReflectiveTypeAdapterFactory.java:226)
我的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)
我的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) {
}
我在其中花费了很多时间,但仍然无法弄清楚。我该如何解决?有什么建议吗?
您的问题在于:val feed = gson.fromJson(body, Feed::class.java)
。这将使用json并尝试反序列化到您提供的类中。但是,Feed
是一个对象,而您的json是数组形式,因此当gson反序列化时,它期望在开始时为{
。相反,它看到的是[
。
有两个选项可以解决此问题:
Feed
对象。Feed
以扩展List<T>
或Array<T>
。API返回Json对象的数组。因此,您需要将其解析为数组。
而不是val feed = gson.fromJson(body, Feed::class.java)
,您应该放置val feed = gson.fromJson(body, Array<Feed>::class.java)
MainAdaptor
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) {
}