rharter / auto-value-gson

AutoValue Extension to add Gson De/Serializer support
Apache License 2.0
603 stars 103 forks source link

Add support for omitting defaults #269

Open fmeum opened 1 year ago

fmeum commented 1 year ago

If a class is annotated with the new @OmitDefaults annotation, which requires a builder, then all properties that have a value set by the default builder method and correspond to a getter function on the builder have their value omitted from the serialized JSON if it matches the default one.

fmeum commented 1 year ago

@rharter A bit of context: This came up over at Bazel while building some kind of generic package manager that heavily relies on auto-value-gson to generate its lockfile. Since we also need to hash the contents of these lockfiles and want them to remain stable as we add new fields, we need some way to omit fields that are at their default values.

The approach taken in this PR felt natural to me, but I am open to suggestions to do this differently.

I also think that https://github.com/rharter/auto-value-gson/issues/268 could be solved by this as well in a backwards compatible way: Omit null-valued properties if and only if the class is annotated with @OmitDefaults (and lift the requirement to have a Builder subclass). Let me know what you think, happy to make the changes to resolve this related issue.