Joseph Hwang
Joseph Hwang

Reputation: 1431

converting java string dot to float number with json annotation

I try to convert string to float with java json annotation.

public class EtlColumnPojo{
    
    @JsonProperty("value")
    private float value;
}

But some value strings are not number, but "." only. So it throws the following exceptions.

com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type float from String ".": not a valid Float value

So I make the custom json deserializer codes.

public class CustomFloatDeserializer extends JsonDeserializer<Float> {

    @Override
    public Float deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        // TODO Auto-generated method stub
        String floatString = p.getText();
        if(floatString.equals(".")) {
            return Float.valueOf(0);
        }
        
        return Float.valueOf(floatString);
    }

}

And I add the custom deserializer like below,

public class EtlColumnPojo{
    
    @JsonDeserialize(using = CustomFloatDeserializer.class)
    @JsonProperty("value")
    private float value;
}

It works successfully without the above exceptions. But I wonder these custom json deserializer codes are efficient. The value is dot only but I am afraid I make too much codes to solve this issue. Is there another way to solve these exceptions with only simple json annotations?

Upvotes: 1

Views: 732

Answers (1)

dariosicily
dariosicily

Reputation: 4547

If you can add to your EtlColumnPojo class a setter you can label it with the same @JsonProperty("value") annotation you're using or as the alternative one JsonSetter annotation:

@JsonProperty("value")
public void setValue(String floatString) {
    value = floatString.equals(".") ? 0 : Float.valueOf(floatString);
}

Upvotes: 1

Related Questions