3

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?

4
  • Note that Java behavior is generally defined around properties, which are defined by the (public) getters and/or setters; whether those properties have backing fields is usually formally irrelevant. Commented May 5, 2022 at 19:53
  • Thanks a lot! This behavior makes much more sense now. Commented May 5, 2022 at 20:08
  • 1
    Just to clarify where the text "totalBalance" is coming from, in the JSON: I assume (but I don't have an official reference/citation) that Jackson is following the JavaBeans naming standards (replace the get, and then make the T lowercase) to convert the method name into a JSON key. (The reverse of what getter code generators typically do.) Someone correct me if wrong? Commented May 5, 2022 at 20:08
  • 1
    @andrewJames that's pretty much it, but also it will convert consecutive initial uppercase letters to lowercase (example getID becomes "id")
    – Bahij.Mik
    Commented May 5, 2022 at 20:19

2 Answers 2

8

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);
1

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.

1
  • This was weird for me at first to achieve serialization/deserialization of objects with this default setup. Now that I learned it , I can try to configure it . Thank you Commented May 5, 2022 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.