Java – duplicate fields in JSON response

I used spring boot Jackson dependency and Lombok in my project. In response, I got duplicate fields because of underscores

This is my model class:

@Getter
 @Setter
 @Accessors(chain = true)
 @NoArgsConstructor
 @ToString
 public class TcinDpciMapDTO {

 @JsonProperty(value = "tcin")
 private String tcin;
 @JsonProperty(value = "dpci")
 private String dpci;

 @JsonProperty(value = "is_primary_tcin_in_dpci_relation")
 private boolean is_primaryTcin = true;

 }

If I were here_ If I use underscores in the primarytcin field, I will get the response of the duplicate field

{
    "_primaryTcin": true,"tcin": "12345","dpci": "12345","is_primary_tcin_in_dpci_relation": true
 }

If I remove the underscore from the field isprimarytcin, I get the correct answer

{
    "tcin": "12345","is_primary_tcin_in_dpci_relation": true
}

Is this because of underline? But are underscores more suitable for variable names?

Solution

This is what your class looks like after delomboking:

public class TcinDpciMapDTO {
    @JsonProperty("tcin")
    private String tcin;
    @JsonProperty("dpci")
    private String dpci;
    @JsonProperty("is_primary_tcin_in_dpci_relation")
    private boolean is_primaryTcin = true;

    public String getTcin() {
        return this.tcin;
    }

    public String getDpci() {
        return this.dpci;
    }

    public boolean is_primaryTcin() {
        return this.is_primaryTcin;
    }

    public TcinDpciMapDTO setTcin(String tcin) {
        this.tcin = tcin;
        return this;
    }

    public TcinDpciMapDTO setDpci(String dpci) {
        this.dpci = dpci;
        return this;
    }

    public TcinDpciMapDTO set_primaryTcin(boolean is_primaryTcin) {
        this.is_primaryTcin = is_primaryTcin;
        return this;
    }

    public TcinDpciMapDTO() {
    }

    public String toString() {
        return "TcinDpciMapDTO(tcin=" + this.getTcin() + ",dpci=" + this.getDpci() + ",is_primaryTcin=" + this.is_primaryTcin() + ")";
    }
}

If the generated property name is not specified, it is generated by stripping the prefix, get if getter is used, or Java field name when serializing the field without getter By default, Jackson uses getters only during serialization Because you put @ jsonproperty on the field, Jackson uses the field and getter and checks whether the field has been serialized by matching the generated property name sequence (the last part is my guess). It does not recognize the field is_ The attribute generated by primarytcin and the attribute getter generated from it are_ Primarytcin () is the same (one is internally named as is_primarytcin and the other is named _primarytcin) – note that if is_ Primarytcin renamed as_ Primarytcin, the problem will disappear

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>