Mapping the same Json key in different variables in the same object
Solution 1:
The issue is due to the fact that your class rate
and ratePPR
fields match the same json rate property either in the deserialization process or serialization process, so as precondition you have to change the name of one of them. One way to solve the problem as from the user Lino's comment below your question is define a JsonCreator
annotated constructor with a float parameter annotated with the @JsonProperty("rate")
and inside define the two fields:
@ToString
@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UsageRate implements Serializable {
@JsonCreator
public UsageRate(@JsonProperty("rate") float rate) {
this.rateIntegerPart = (int) rate;
this.ratePPR = rate;
}
@JsonIgnore
private int rateIntegerPart;
@JsonProperty("rate")
private Float ratePPR;
}
The JsonIgnore
annotation excludes the rateIntegerPart
from the serialization :
//json = {"rate":10.0}
UsageRate rate = mapper.readValue(json, UsageRate.class);
System.out.println(rate); //it prints UsageRate(rateIntegerPart=10, ratePPR=10.0)
System.out.println(mapper.writeValueAsString(rate)); // it prints {"rate":10.0}