【问题标题】:Parsing a jsonrray into object using moshi with Retrofit and Kotlin使用带有 Retrofit 和 Kotlin 的 moshi 将 jsonarray 解析为对象
【发布时间】:2020-07-16 16:58:49
【问题描述】:

我正在尝试使用 Kotlin Coroutines 解析 JSON 数组的 Moshi 库。

代码使用

 fun retrofitIndia(baseUrl : String) : Retrofit = Retrofit.Builder()
        .client(clientIndia)
        .baseUrl(baseUrl)
        .addConverterFactory(MoshiConverterFactory.create())
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .build()

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

java.lang.IllegalArgumentException: Unable to create converter for java.util.ArrayList<data.india.Delta2>

我从 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)
            }
        }

【问题讨论】:

  • 您能否提供从哪一行抛出错误?还是显示完整的堆栈跟踪?
  • 我有一个 jsonArray 作为要使用的 json 输出......当我从 Kotlin 协程 GlobalScope.launch(Dispatchers.Main) { val statsRequest = iservice.getStats() 调用它时,我的错误出现在这里try { val response = statsRequest.await() if(response.){ val statsResponse = response.body() //This is single object Tmdb Movie response } }
  • @AnimeshSahu:有没有从 Moshi 解析 JSONArray 的想法?
  • 不认识的人,没有使用过那些库,也许悬赏这个问题,采取+1。
  • 您的 JSON 响应格式(示例 json 响应)和解析器类是什么?完整的堆栈跟踪也会有所帮助..

标签: android arrays json kotlin moshi


【解决方案1】:

我认为协程没有任何解析错误,请尝试关注Reading Json lists using Moshi

快速 sn-p 看起来像:

// Single item declaration 
class SingleListItem(val title: String, val number: Int)

private var listMyData = Types.newParameterizedType(MutableList::class.java, SingleListItem::class.java)
private val adapter: JsonAdapter<List<SingleListItem>> = Moshi.Builder().add(KotlinJsonAdapterFactory()).build().adapter(listMyData)

【讨论】:

    【解决方案2】:

    你应该把类型设为List&lt;T&gt;,Moshi 只支持集合接口,不支持具体的集合类,如ArrayList&lt;T&gt;LinkedList&lt;T&gt; 等。其他类型的集合也是如此:使用Set&lt;T&gt;而不是HashSet&lt;T&gt;,和Map&lt;K, V&gt;而不是HashMap&lt;K, V&gt;等。

    【讨论】:

      猜你喜欢
      • 2021-08-24
      • 2018-07-26
      • 1970-01-01
      • 2018-07-15
      • 2021-02-03
      • 2021-04-24
      • 2020-01-24
      • 1970-01-01
      • 2019-04-20
      相关资源
      最近更新 更多