使用 moshi 结合 Retrofit 和 Kotlin 将 jsonrray 解析为对象

Yat*_*tin 6 arrays android json kotlin moshi

我正在尝试使用 Kotlin Coroutines 使用 Moshi Library for JSON Array 进行解析。

代码使用

 fun retrofitIndia(baseUrl : String) : Retrofit = Retrofit.Builder()
        .client(clientIndia)
        .baseUrl(baseUrl)
        .addConverterFactory(MoshiConverterFactory.create())
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .build()
Run Code Online (Sandbox Code Playgroud)

我在解析 JSON Array 的数据类时遇到问题。我对 JSON 对象使用了相同的方法,它工作正常,但在数组期间,它崩溃了下面是崩溃线

java.lang.IllegalArgumentException: Unable to create converter for java.util.ArrayList<data.india.Delta2>
Run Code Online (Sandbox Code Playgroud)

我从 Globallaunch 协程调用,但失败了

代码 :

 GlobalScope.launch(Dispatchers.Main) {
            val statsRequest = i.getStats()
            try {
                val response = statsRequest.await()
               if(response.){
                    val statsResponse = response.body() //This is single object Tmdb Movie response


                    Log.i("stats",""+statsResponse)
                }else{
                    Log.d("MainActivity ",response.errorBody().toString())
                }
            }catch (e: Exception){
                Log.e("Exception",e.localizedMessage)
            }
        }
Run Code Online (Sandbox Code Playgroud)

小智 3

您应该将类​​型设置为List<T>,Moshi 只支持集合接口,而不支持具体的集合类ArrayList<T>,例如LinkedList<T>、 等。其他类型的集合也是如此:使用Set<T>代替HashSet<T>Map<K, V>代替HashMap<K, V>等。