Archimedes Trajano
Archimedes Trajano

Reputation: 41220

Handling boolean values and empty strings for a property in Jackson?

I have a JSON property that can be one of

{ "observed": true }
{ "observed": false }
{ "observed": "" }

I'd like to map it so that in Java it will one of "true", "false" or ""

@JsonProperty("observed")
private String observedValue;

Then I'll just make a getter that would give me a

public Optional<Boolean> getObservedOpt() {
    if ("".equals(observedValue)) {
       return Optional.empty();
    } else {
       return Optional.of(Boolean.parseBoolean(observedValue));
    }
}

However, I am not sure how to make it converted true and false into strings. Or perhaps there's a more elegant way of doing it without the string comparison.

Upvotes: 2

Views: 1739

Answers (2)

dassum
dassum

Reputation: 5093

One solution could be using Custom JsonDeserializer

public static class StringBooleanDeserializer extends JsonDeserializer<String> {
        @Override
        public String deserialize(JsonParser parser, DeserializationContext context) throws IOException {
            if(parser.getValueAsBoolean()){
                return "true";
            }else{
                if(parser.getTextLength()==0) {
                    return parser.getText();
                }else{
                    return "false";
                }

            }
        }
    }

@JsonProperty("observed")
@JsonDeserialize(using=StringBooleanDeserializer.class)
private String observedValue;

Similarly, you can also write custom JSON Serializer.

Upvotes: 0

Ryuzaki L
Ryuzaki L

Reputation: 39978

I would suggest configure object mapper with this feature ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, so in case of empty string it will be assigned to null

ObjectMapper mapper = new ObjectMapper()
    .enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

And you can happily declare this field as Boolean type, be aware in case of empty string this field value will be null

@JsonProperty("observed")
private Boolean observedValue;

Upvotes: 3

Related Questions