美文网首页Spring Boot
Spring WebClinet自定义Json解析器

Spring WebClinet自定义Json解析器

作者: EasyNetCN | 来源:发表于2020-01-05 20:01 被阅读0次

    自定义ObjectMapper

    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    
    import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
    
    import com.fasterxml.jackson.databind.DeserializationFeature;
    import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
    import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
    
    @Configuration
    public class JsonConfig {
    
        @Bean
        @Primary
        public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder(JacksonProperties jacksonProperties) {
            var builder = new Jackson2ObjectMapperBuilder();
    
            builder.serializerByType(LocalDateTime.class,
                    new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(jacksonProperties.getDateFormat())));
            builder.deserializerByType(LocalDateTime.class,
                    new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(jacksonProperties.getDateFormat())));
            builder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    
            return builder;
        }
    }
    

    配置WebClient的自定义的编码解码策略

    import org.springframework.cloud.client.loadbalancer.LoadBalanced;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.codec.json.Jackson2JsonDecoder;
    import org.springframework.http.codec.json.Jackson2JsonEncoder;
    import org.springframework.web.reactive.function.client.WebClient;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    @Configuration
    public class WebClientConfig {
        @Bean
        @LoadBalanced
        WebClient.Builder loadBalanced(ObjectMapper objectMapper) {
            return WebClient.builder().codecs(configurer -> {
                var jackson2JsonDecoder = new Jackson2JsonDecoder(objectMapper);
    
                jackson2JsonDecoder.setMaxInMemorySize(-1);
    
                configurer.defaultCodecs().jackson2JsonDecoder(jackson2JsonDecoder);
                configurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper));
            });
        }
    
    }
    

    相关文章

      网友评论

        本文标题:Spring WebClinet自定义Json解析器

        本文链接:https://www.haomeiwen.com/subject/esycactx.html