Search code examples
javajsonserializationfasterxml

@JsonProperty seems to only work for non boolean members


I have an object I'm trying to map to JSON and everything seems to work marvelously, except for boolean members, as we can see below:

public class Foo implements Serializable {

    @JsonProperty("this_does_not_work")
    private boolean isBar;

    @JsonProperty("this_works")
    private int bar;

    @JsonProperty("this_works_too")
    public boolean isBar() {
        return isBar;
    }

}

This would be serialized to this:

{
    this_works: ...,
    this_works_too: ...    
}

Why do boolean members can't have a @JsonProperty (but their getters do)?


Solution

  • Summarising the statements from comments: if you change your boolean field name to enabled

    @JsonProperty("custom_name")
    private boolean enabled;
    
    public boolean isEnabled() {
        return enabled;
    }
    
    public void setEnabled(boolean isEnabled) {
        this.enabled = isEnabled;
    }
    

    it will give desired output { "custom_name" : true }

    The original problem is not following java field naming conventions:

    @JsonProperty("custom_name")
    @Column(name = "fl_enabled")
    private boolean isEnabled;
    
    public boolean isEnabled() {
        return isEnabled;
    }
    
    public void setEnabled(boolean isEnabled) {
        this.isEnabled = isEnabled;
    }
    

    When FasterXML serializes an object, it looks for fields and getters.

    In your case, it found boolean field isEnabled and serialized it with custom_name.

    Then it excluded getter of this boolean field from processing - possible getter names to exclude are getIsEnabled and 'isIsEnabled' - you don't have any.

    Then it finds method isEnabled that looks like a getter for field enabled. So it takes its value and serializes it with key enabled.

    So again, the problem is you should not name boolean fields with prefix is.