Moshi无法解析可为空的 [英] Moshi cannot parse nullable

查看:192
本文介绍了Moshi无法解析可为空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好)希望你能帮助我. 我使用Kotlin(Retrofit2 + moshi)从"https://api.spacexdata.com/v3/launches"获取数据并解析它. 一切都很好(我得到的属性是:flight_number,mission_name),但是某些属性的属性为"null",例如"mission_patch". -有111个对象.它们中的109个具有"mission_patch"处的数据,2个对象没有数据("mission_patch":空). 我的问题:moshi无法正确解析包含null的属性.

Hello) Hope you can help me. Using kotlin (Retrofit2 + moshi) i getting data from "https://api.spacexdata.com/v3/launches" and parsing it. All is going fine (i getting attributes like: flight_number, mission_name), but some attributes have "null", like "mission_patch" - there are 111 objects. 109 of them have data at "mission_patch", 2 objects dont have it ("mission_patch":null). My problem: moshi cannot parse correctly attribute which contains null.

如果我使用:

data class SpaceXProperty(
   val  flight_number: Int,
   val mission_name: String,
   val mission_patch: String)

我收到错误:失败:必需值" mission_patch";缺少$ [1]" -好的,我将数据类更改为下一个:

i getting error: "Failure: Required value "mission_patch" missing at $[1]" - OK i changed data class to next:

data class SpaceXProperty(
       val  flight_number: Int,
       val mission_name: String,
       val mission_patch: String?)

我正在获取数据,但是每个对象都具有mission_patch = null.这是不正确的,因为只有2个对象的task_patch = null而不是全部.

with this i getting data, but every object have mission_patch=null. This is uncorrect, bc only 2 objects have mission_patch=null, not all.

请帮帮我.我是科特林的新人,我做错了什么?

Help me please. im new at kotlin, what i doing wrong?

我的改造服务:

private const val BASE_URL = "https://api.spacexdata.com/v3/"


private val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()

private val retrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    //.addConverterFactory(ScalarsConverterFactory.create())
    .baseUrl(BASE_URL)
    .build()

 interface SpaceXApiService {
    @GET("launches")
    suspend fun getProperties():List<SpaceXProperty>
}

 object SpaceXApi{
    val retrofitservice :SpaceXApiService by lazy {
    retrofit.create(SpaceXApiService::class.java)
    }
}

推荐答案

mission_patch不在flight_number等根对象中,而是嵌套在links内部.因此,您的模型应该匹配.试试这个:

mission_patch is not in the root object like flight_number etc. It's nested inside links. So your model should match. Try this:

data class SpaceXProperty(
       val  flight_number: Int,
       val mission_name: String,
       val links: Links) {

    data class Links(val mission_patch: String?)
}

这篇关于Moshi无法解析可为空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆