Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson renames primitive boolean field by removing 'is'

Tags:

java

json

jackson

This is a slightly late answer, but may be useful for anyone else coming to this page.

A simple solution to changing the name that Jackson will use for when serializing to JSON is to use the @JsonProperty annotation, so your example would become:

public class MyResponse implements Serializable {

    private boolean isSuccess;

    @JsonProperty(value="isSuccess")        
    public boolean isSuccess() {
        return isSuccess;
    }

    public void setSuccess(boolean isSuccess) {
        this.isSuccess = isSuccess;
    }
}

This would then be serialised to JSON as {"isSuccess":true}, but has the advantage of not having to modify your getter method name.

Note that in this case you could also write the annotation as @JsonProperty("isSuccess") as it only has the single value element


I recently ran into this issue and this is what I found. Jackson will inspect any class that you pass to it for getters and setters, and use those methods for serialization and deserialization. What follows "get", "is" and "set" in those methods will be used as the key for the JSON field ("isValid" for getIsValid and setIsValid).

public class JacksonExample {   

    private boolean isValid = false;

    public boolean getIsValid() {
        return isValid;
    }

    public void setIsValid(boolean isValid) {
        this.isValid = isValid;
    }
} 

Similarly "isSuccess" will become "success", unless renamed to "isIsSuccess" or "getIsSuccess"

Read more here: http://www.citrine.io/blog/2015/5/20/jackson-json-processor


Using both annotations below, forces the output JSON to include is_xxx:

@get:JsonProperty("is_something")
@param:JsonProperty("is_something")

When you are using Kotlin and data classes:

data class Dto(
    @get:JsonProperty("isSuccess") val isSuccess: Boolean
)

You might need to add @param:JsonProperty("isSuccess") if you are going to deserialize JSON as well.