Muyoo Muyoo - 1 month ago 12
Java Question

extra data while parsing boolean value in json by using Jackson

When I'm parsing boolean value in JSON by using Jackson, I not only get my expected data, but also an extra key-value data. I want to deserialize the JSON into Java Beans and then serialize it into a String again after processing it. The extra data is in the finally result.Here is my JSON data:

{"is_charging": true}


But I get this after I parse it and then serialize it:

{"is_charging": true, "charging": true}


And here is my Java bean:

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Data {
@JsonProperty("is_charging")
public boolean isCharging;
}


However, if I don't use the
@JsonProperty
, it can not deserialize the "is_charging" and deserialize it as false by default.

How can I solve this? Thanks!

Answer

It is the lombok.Getter and lombok.Setter annotations that cause the issue.

public class Data {
    @JsonProperty("is_charging")
    public boolean isCharging; 
}

objectMapper.writeValueAsString(new Data());

Works as expected.

The problem occurs when the @Getter and @Setter annotations are added.

I don't have experience with this lombok library but as far as I understand it creates getter and setter methods for you.

By configuring objectMapper you can disable auto detecting of getter and setter methods so only fields can be serialized and deserialized.

@Getter
@Setter
public class Data {

    @JsonProperty("is_charging;")
    public boolean isCharging;

}

public static void main(String... args) throws JsonProcessingException, IOException {

    ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    objectMapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
    objectMapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false);

    Data data = objectMapper.readValue("{\"is_charging\": true}", Data.class);

    System.out.print(objectMapper.writeValueAsString(data));
}

Outputs:

{"is_charging":true}

Note that only objectMapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false); is required in your case. Others are provided for reference in case you need them.

Comments