Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nullable fields not serialized #180

Open
Knotworking opened this issue Oct 21, 2020 · 1 comment
Open

Nullable fields not serialized #180

Knotworking opened this issue Oct 21, 2020 · 1 comment

Comments

@Knotworking
Copy link

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.

@Knotworking
Copy link
Author

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant