rharter/auto-value-moshi

Nullable fields not serialized

Knotworking opened this issue · 1 comments

We require sending null values for fields within our request body json to our API. However, the nullable fields never get serialized. From our investigations this seems to be an auto-value-moshi issue.

I think our use case and issue is similar to issue-126.

We have tried the proposed solution from the issue above, but the problem is that within the generated toJson method, the writer (which has serializeNulls = true) is only accessed within a field != null if statement, so the nullable field is never added to the json object to be written.

Here is a sample project we've written to demonstrate the issue. Please see the SerializeTest test class.

So that you don't need to checkout our sample project and build it, here is the relevant code I think.

Our model class (Issue), we're intending to write null for the field title

@JsonClass(generateAdapter = true, generator = "avm")
@AutoValue
abstract class Issue {

    abstract fun getId(): String

    @Nullable
    abstract fun getTitle(): String?

    abstract fun toBuilder(): Builder

    @AutoValue.Builder
    abstract class Builder {
        abstract fun id(value: String): Builder
        abstract fun title(value: String?): Builder
        abstract fun build(): Issue
    }

    companion object {
        fun builder(): Builder = AutoValue_Issue.Builder()

        @JvmStatic
        fun jsonAdapter(moshi: Moshi): JsonAdapter<Issue> {
            return IssueJsonAdapter(moshi).serializeNulls()
        }
    }
}

The generated toJson method in the adapter. As you can see here the title field is only written when title != null

@Override
  public void toJson(JsonWriter writer, Issue value) throws IOException {
    writer.beginObject();
    writer.name("id");
    this.idAdapter.toJson(writer, value.getId());
    String title = value.getTitle();
    if (title != null) {
      writer.name("title");
      this.titleAdapter.toJson(writer, title);
    }
    writer.endObject();
  }

So, are we missing something, is it possible to serialize null values?