Moshi cannot parse nullable

Viewed 194

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 Answers

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