Skip to content

Automatically serialize nulls when a nullable property has a non-null default value #1358

Description

@dlew

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:

  1. It is nullable.
  2. It has a non-null default value.
  3. The current value is null.

Thus avoiding this lack of symmetry. (In the above example, it would mean that toJson(Foo(null)) == "{ \"bar\": null }")

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions