Issue
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?
Solution
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);
Answered By - Bahij.Mik
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)