5

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

ligi
  • 39,001
  • 44
  • 144
  • 244

3 Answers3

5

The problem was actually this bug in moshi:

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

hat tip @cketti for pointing me to the issue.

ligi
  • 39,001
  • 44
  • 144
  • 244
1

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

json

{
"bar": null
}

so it should be

adapter.fromJson("{"bar":null}")
sasikumar
  • 12,540
  • 3
  • 28
  • 48
  • thanks - but this a) produces the same error and b) is not what I want - I want to be able to omit the field in the json – ligi Nov 12 '19 at 21:31
1
  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
     )
    
CoolMind
  • 26,736
  • 15
  • 188
  • 224