java – @JsonAutoDetect immutable objects

Question:

There is a class:

@JsonAutoDetect
public class Payer {

    private Long Id;
    private Long companyId;
    private String name;

    public void setId(Long Id) {
        this.Id = Id;
    }

    public void setCompanyId(Long companyId) {
        this.companyId = companyId;
    }

    public void setName(String name) {
        this.name = name;
    } 
}

And in this form everything works, but how to make it immutable, avoiding the mapping in the constructor? Is it possible to somehow use @JsonAutoDetect ?

public class Payer {

    private final Long Id;
    private final Long companyId;
    private final String name;

    @JsonCreator
    public PayerDto(@JsonProperty("") Long id, 
                    @JsonProperty("") Long companyId, 
                    @JsonProperty("") String name) {
        Id = id;
        this.companyId = companyId;
        this.name = name;
    }
}

Answer:

If you use lombock, you can do this:

@Builder()
@Data
@JsonDeserialize(builder = PayerDto.PayerDtoBuilder.class)
public static class PayerDto {
    private final Long id;
    private final Long companyId;
    private final String name;
    @JsonPOJOBuilder(withPrefix = "")
    public static final class PayerDtoBuilder {
    }
}
Scroll to Top