I have a class with the following fields and their respective getters, plus an additional method getTotalBalance
for which I don't have any field but a custom implementation.
public class demo{
private String balance;
private String blockedBalace;
private String futureBalance;
private String availableBalance;
//getters for previous fields
public String getTotalBalance(){
//something..
}
When I serialize an object of this class I get the following JSON output.
{
"balance": "12.30",
"blockedBalance":"23.45",
"futureBalance" :"56.22",
"availableBalance" :"12.30",
"totalBalance" : "34.11"
}
Even if I didn't declare a field for totalBalance
, I've got this serialized in the end. How is it possible?
CodePudding user response:
Jackson by default uses the getters for serializing and setters for deserializing.
You can use @JsonIgnore
over your getter method to ignore it, OR you can configure your object mapper to use the fields only for serialization/des:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
CodePudding user response:
Jackson doesn't (by default) care about fields. It will simply serialize everything provided by getters and deserialize everything with a matching setter. What those getters/setters do is of no consequence.
Mind you though, that every little thing about Jackson can be deeply customized and configured, so I'm only talking about the default setup.