Tarni Sharma
Tarni Sharma

Reputation: 51

Not able to deserialise boolean values properly through Jackson

I am using the following jackson mapper in my project.

org.codehaus.jackson jackson-mapper-asl 1.9.13

My issue that whenever I try to convert a json string into an object, I am not able to map the boolean values properly. Its a very peculiar problem. If my attribute name starts with "is" e.g "isFlag":true, the jackson is not reading it. If I change the attribute name to "Flag":true, correct object is getting created.

Reference Json :

{"ticketNumber": "0970897760","chartPrepared": true,"isFlag": true}

Reference Class :

class TestClass {
        String ticketNumber;
        boolean chartPrepared;
        boolean isFlag;

        public boolean isChartPrepared() {
            return chartPrepared;
        }
        public void setChartPrepared(boolean chartPrepared) {
            this.chartPrepared = chartPrepared;
        }
        public boolean isFlag() {
            return isFlag;
        }
        public void setFlag(boolean isFlag) {
            this.isFlag = isFlag;
        }
        public String getTicketNumber() {
            return ticketNumber;
        }
        public void setTicketNumber(String ticketNumber) {
            this.ticketNumber = ticketNumber;
        }
    }
}

Function :

TestClass obj = mapper.readValue(text, TestClass.class);
System.out.println(obj.getTicketNumber()+" "+obj.isChartPrepared()+" "+obj.isFlag());

Actual Output:

0970897760 true false 

Expected Output:

0970897760 true true

Upvotes: 0

Views: 3401

Answers (3)

aravinth
aravinth

Reputation: 11

Here the problem is the getter method name isFlag(). It doesn't matter whether you use boolean or Boolean, jackson expects getter to start with get***() like getIsFlag() in this example. It is always better to use Boolean because boolean(primitive) will be considered optional if you don't include exclusively and it will consider default value "false".

If you change your getter method to getIsFlag(), it will deserialize without any issues.

Upvotes: 1

WesternGun
WesternGun

Reputation: 12728

I think it is because Jackson expect getXxx() even for boolean, so it's always better to use Boolean instead of boolean, because when you generate the getter/setter in any IDE, you only get isFlag() for boolean primitive type, but if is Boolean, you will have getFlag().

Upvotes: 3

Tarni Sharma
Tarni Sharma

Reputation: 51

Thanks for the reply BusyAnt. I figured out a better solution. Explicitly Adding @JsonProperty("isFlag) in the TestClass solved this problem.

@JsonProperty("isFlag")
boolean isFlag;

Upvotes: 5

Related Questions