ligi
ligi

Reputation: 39529

moshi nullable list fails with "required value"

The following works:

package com.squareup.moshi.problem

import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi

@JsonClass(generateAdapter = true)
data class Foo(
        val bar: String?
)

fun main() {
    val adapter=Moshi.Builder().build().adapter<Foo>(Foo::class.java)
    adapter.fromJson("{}")
}

but when using a list it fails:

package com.squareup.moshi.problem

import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi

@JsonClass(generateAdapter = true)
data class Foo(
        val bar: List<String>?
)

fun main() {
    val adapter=Moshi.Builder().build().adapter<Foo>(Foo::class.java)
    adapter.fromJson("{}")
}

with:

Exception in thread "main" com.squareup.moshi.JsonDataException: Required value 'bar' missing at $
        at com.squareup.moshi.internal.Util.missingProperty(Util.java:605)
        at com.squareup.moshi.problem.FooJsonAdapter.fromJson(FooJsonAdapter.kt:44)
        at com.squareup.moshi.problem.FooJsonAdapter.fromJson(FooJsonAdapter.kt:16)
        at com.squareup.moshi.internal.NullSafeJsonAdapter.fromJson(NullSafeJsonAdapter.java:40)
        at com.squareup.moshi.JsonAdapter.fromJson(JsonAdapter.java:43)
        at com.squareup.moshi.problem.MoshiProblemKt.main(MoshiProblem.kt:13)
        at com.squareup.moshi.problem.MoshiProblemKt.main(MoshiProblem.kt)

How can I make it work for a list? Here is a repo showing the problem: https://github.com/ligi/moshi_problem

Upvotes: 5

Views: 10863

Answers (3)

CoolMind
CoolMind

Reputation: 28793

  1. Make sure you set a corresponding model.

    @GET("/info/")
    suspend fun getInfo(@Query("id")): Info
    

Maybe it shouldn't be Info, but another type. Also there might be changes in backend and structure of the model had changed.

  1. Make sure a required field in the model can be null. For instance, if Info is a data class with two fields: id and name, a name can be null in some cases.

     @JsonClass(generateAdapter = true)
     data class Info(
         @Json(name = "id")
         val id: Int,
    
         @Json(name = "name")
         val name: String? // "?" means nullable
     )
    

Upvotes: 2

ligi
ligi

Reputation: 39529

The problem was actually this bug in moshi:

https://github.com/square/moshi/issues/990

hat tip @cketti for pointing me to the issue.

Upvotes: 6

Sasi Kumar
Sasi Kumar

Reputation: 13348

If the bar json value is null means it should be like this

json

{
"bar": null
}

so it should be

adapter.fromJson("{"bar":null}")

Upvotes: 1

Related Questions