Moshi cannot parse nullable

一曲冷凌霜 提交于 2021-01-28 11:30:21

问题


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.

if i using:

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

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?)

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?

My retrofit service:

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

回答1:


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?)
}


来源:https://stackoverflow.com/questions/65559580/moshi-cannot-parse-nullable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!