Java – Jackson renames the original Boolean field by deleting ‘is’
This may be repeated But I couldn't find a solution
I have a class
public class MyResponse implements Serializable {
private boolean isSuccess;
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
}
Getters and setters are generated by eclipse
In another class, I set the value to true and write it as a JSON string
System.out.println(new ObjectMapper().writeValueAsString(myResponse));
In JSON, the key is {success ": true}
The key I want is as success itself Does Jackson use the setter method when serializing? How to make the key as the field name itself?
Solution
This is a later answer, but it may be useful for anyone who comes to this page
A simple solution to change the name Jackson will use to serialize JSON is to use the @ jsonproperty annotation, so your example will be:
public class MyResponse implements Serializable {
private boolean isSuccess;
@JsonProperty(value="isSuccess")
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
}
This will be serialized as JSON as {"issuccess": true}, but has the advantage of not having to modify the getter method name
Note that in this case, you can also write the comment @ jsonproperty ("issuccess") because it has only a single value element
