The following code, which writes an object to JSON then parses it again, fails at an equality check:
data class Foo(val bar: String? = "oops")
val adapter = Moshi.Builder().build().adapter(Foo::class.java)
val foo = Foo(bar = null)
val json = adapter.toJson(foo)
val foo2 = adapter.fromJson(json)
check(foo == foo2) // Fails
The reason it fails is because toJson(Foo(null)) == "{}", yet fromJson("{}") == Foo("oops"). That happens only because we're mixing a nullable property has a non-null default value.
One solution is to serialize nulls. Theoretically, Moshi could serialize nulls on any property where:
- It is nullable.
- It has a non-null default value.
- The current value is
null.
Thus avoiding this lack of symmetry. (In the above example, it would mean that toJson(Foo(null)) == "{ \"bar\": null }")
The following code, which writes an object to JSON then parses it again, fails at an equality check:
The reason it fails is because
toJson(Foo(null)) == "{}", yetfromJson("{}") == Foo("oops"). That happens only because we're mixing a nullable property has a non-null default value.One solution is to serialize nulls. Theoretically, Moshi could serialize nulls on any property where:
null.Thus avoiding this lack of symmetry. (In the above example, it would mean that
toJson(Foo(null)) == "{ \"bar\": null }")