auto-value-gson icon indicating copy to clipboard operation
auto-value-gson copied to clipboard

@AutoValue.Builder generates objects with all fields

Open ratheeshcn opened this issue 1 year ago • 2 comments

@eamonnmcmanus I am having an issue on Builder method, it generates the json with all the fields instead of the values we set on builder method.

these are my dependencies

const val autoValue = "com.google.auto.value:auto-value:1.10"
const val autoParcel = "com.ryanharter.auto.value:auto-value-parcel:0.2.9"
const val autoGson = "com.ryanharter.auto.value:auto-value-gson:1.3.1"

here is my data class


@AutoValue
public abstract class CreateBuyerBody implements Parcelable{


    @SerializedName("first_name")
    @Nullable
    public abstract  String firstName();

    @SerializedName("last_name")
    @Nullable
    public abstract  String lastName();

    @SerializedName("phone_numbers")
    @Nullable
    public abstract 
    List<PhoneNumber> phoneNumbers();

    @SerializedName("email_addresses")
    @Nullable
    public abstract  List<EmailAddress> emailAddresses();


    public static @NonNull TypeAdapter<CreateBuyerBody> typeAdapter(@NonNull Gson gson) {
        return new $AutoValue_CreateBuyerBody.GsonTypeAdapter(gson);
    }

    public static Builder builder() {
        return new $$AutoValue_CreateBuyerBody.Builder();
    }

    @AutoValue.Builder
    public static abstract class Builder {


        public abstract Builder firstName(@Nullable String firstName);
        public abstract Builder lastName(@Nullable String lastName);
        public abstract Builder phoneNumbers(@Nullable List<PhoneNumber> phoneNumbers);
        public abstract Builder emailAddresses(@Nullable List<EmailAddress> emailAddresses);
         public abstract CreateBuyerBody build();
    }
}

while accessing the builder method

CreateBuyerBody.Builder builder = CreateBuyerBody.builder();
builder.firstName("John");

it generates this

{"first_name":"John","last_name":null,"phone_numbers":null,"email_addresses":null}

instead of this

{"first_name":"John"}

Can you help me where i get wrong on this ? thanks in advance.

ratheeshcn avatar Jul 07 '23 10:07 ratheeshcn

I think this is a question for the project owner, @rharter. As I mentioned in the earlier discussion, auto-value-gson should possibly respect Gson.serializeNulls(), only serializing null properties if it is true. But that would potentially be an incompatible change.

eamonnmcmanus avatar Jul 07 '23 18:07 eamonnmcmanus

Thanks for the report. As @eamonnmcmanus mentioned, respecting GSON's serializeNulls() setting is most appropriate, and it looks like that would require querying for that value here and only emitting the null value if it's true.

As this project has been dormant for quite a number of years, I don't have availability to work on this, but PRs are welcome.

rharter avatar Jul 07 '23 18:07 rharter