Spring Boot

Spring WebClinet自定义Json解析器

2020-01-05  本文已影响0人  EasyNetCN

自定义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));
        });
    }

}
上一篇 下一篇

猜你喜欢

热点阅读