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

前端 未结 3 1376
别那么骄傲
别那么骄傲 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:47

    With all respect to accepted answer, there is a way to get rid of those @JsonDeserialize annotations.

    You need to register the custom deserializer in the ObjectMapper.

    Following the tutorial from official web-site you just do something like:

        ObjectMapper mapper = new ObjectMapper();
        SimpleModule testModule = new SimpleModule(
                "DoubleCustomDeserializer",
                new com.fasterxml.jackson.core.Version(1, 0, 0, null))
                .addDeserializer(Double.class, new JsonDeserializer() {
                    @Override
                    public Double deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                        String valueAsString = jp.getValueAsString();
                        if (StringUtils.isEmpty(valueAsString)) {
                            return null;
                        }
    
                        return Double.parseDouble(valueAsString.replaceAll(",", "\\."));
                    }
                });
        mapper.registerModule(testModule);
    

    If you're using Spring Boot there is a simpler method. Just define the Jackson2ObjectMapperBuilder bean somewhere in your Configuration class:

    @Bean
    public Jackson2ObjectMapperBuilder jacksonBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    
        builder.deserializerByType(Double.class, new JsonDeserializer() {
            @Override
            public Double deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                String valueAsString = jp.getValueAsString();
                if (StringUtils.isEmpty(valueAsString)) {
                    return null;
                }
    
                return Double.parseDouble(valueAsString.replaceAll(",", "\\."));
            }
        });
    
        builder.applicationContext(applicationContext);
        return builder;
    }
    

    and add the custom HttpMessageConverter to the list of WebMvcConfigurerAdapter message converters:

     messageConverters.add(new MappingJackson2HttpMessageConverter(jacksonBuilder().build()));
    

提交回复
热议问题