How to deserialize a float value with a localized decimal separator with Jackson

前端 未结 3 1309
别那么骄傲
别那么骄傲 2020-12-16 22:16

The input stream I am parsing with Jackson contains latitude and longitude values such as here:

{
    \"name\": \"pr         


        
3条回答
  •  有刺的猬
    2020-12-16 22:48

    I came up with the following solution:

    public class FlexibleFloatDeserializer extends JsonDeserializer {
    
        @Override
        public Float deserialize(JsonParser parser, DeserializationContext context)
                throws IOException {
            String floatString = parser.getText();
            if (floatString.contains(",")) {
                floatString = floatString.replace(",", ".");
            }
            return Float.valueOf(floatString);
        }
    
    }
    

    ...

    public class Product {
    
        @JsonProperty("name")
        public String name;
        @JsonDeserialize(using = FlexibleFloatDeserializer.class)
        @JsonProperty("latitude")
        public float latitude;
        @JsonDeserialize(using = FlexibleFloatDeserializer.class)
        @JsonProperty("longitude")
        public float longitude;
    
    }
    

    Still I wonder why I it does not work when I specify the return value class as as = Float.class as can be found in the documentation of JsonDeserialize. It reads as if I am supposed to use one or the other but not both. Whatsoever, the docs also claim that as = will be ignored when using = is defined:

    if using() is also used it has precedence (since it directly specified deserializer, whereas this would only be used to locate the deserializer) and value of this annotation property is ignored.

提交回复
热议问题