文章目录
- 1.自定义反序列化器
- 2.配置类与自定义 ObjectMapper
- 客户端
需求:OpenFeign配置自定义decode,解析http请求返回的时间字符串
1.自定义反序列化器
Date 自定义反序列化器
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;public class MultiFormatDateDeserializer extends JsonDeserializer<Date> {private static final List<String> FORMATS = Arrays.asList("yyyy-MM-dd HH:mm:ss","yyyy-MM-dd'T'HH:mm:ss","yyyy-MM-dd","MM/dd/yyyy","dd-MM-yyyy");@Overridepublic Date deserialize(JsonParser parser, DeserializationContext context) throws IOException {String dateString = parser.getText();for (String format : FORMATS) {try {return new SimpleDateFormat(format).parse(dateString);} catch (ParseException ignored) {// 尝试下一个格式}}System.err.println("Unparseable date: " + dateString);throw new IOException("Unparseable date: " + dateString);}
}
LocalDate 自定义反序列化器
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;public class MultiFormatLocalDateDeserializer extends JsonDeserializer<LocalDate> {private static final List<DateTimeFormatter> FORMATTERS = Arrays.asList(DateTimeFormatter.ISO_LOCAL_DATE, DateTimeFormatter.ofPattern("MM/dd/yyyy"), DateTimeFormatter.ofPattern("dd-MM-yyyy"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") );@Overridepublic LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {String dateString = parser.getText();for (DateTimeFormatter formatter : FORMATTERS) {try {return LocalDate.parse(dateString, formatter);} catch (Exception ignored) {// 尝试下一个格式}}throw new IOException("Unparseable date: " + dateString);}
}
LocalDateTime 自定义反序列化器
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;public class MultiFormatLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {private static final List<DateTimeFormatter> FORMATTERS = Arrays.asList(DateTimeFormatter.ISO_LOCAL_DATE_TIME, // yyyy-MM-dd'T'HH:mm:ssDateTimeFormatter.ISO_LOCAL_DATE, // yyyy-MM-ddDateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm a"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") );@Overridepublic LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {String dateString = parser.getText();for (DateTimeFormatter formatter : FORMATTERS) {try {return LocalDateTime.parse(dateString, formatter);} catch (Exception ignored) {// 尝试下一个格式}}throw new IOException("Unparseable date: " + dateString);}
}
2.配置类与自定义 ObjectMapper
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import feign.Logger;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import org.apache.kafka.common.utils.Java;
import org.springframework.context.annotation.Bean;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;/*** <p>** </p>** @author pengapeng* @since 2024-12-13*/
public class CustomFeignConfig {@Beanpublic ObjectMapper customObjectMapper() {ObjectMapper objectMapper = new ObjectMapper();// 注册 Java 时间模块JavaTimeModule javaTimeModule = new JavaTimeModule();// 注册自定义反序列化器javaTimeModule.addDeserializer(LocalDateTime.class, new MultiFormatLocalDateTimeDeserializer());javaTimeModule.addDeserializer(LocalDate.class, new MultiFormatLocalDateDeserializer());javaTimeModule.addDeserializer(Date.class, new MultiFormatDateDeserializer());objectMapper.registerModule(javaTimeModule);return objectMapper;}@Beanpublic Decoder feignDecoder() {ObjectMapper customObjectMapper = customObjectMapper();System.out.println("Using Custom Decoder with ObjectMapper: " + customObjectMapper);return new JacksonDecoder(customObjectMapper);}@Beanpublic Encoder feignEncoder() {ObjectMapper customObjectMapper = customObjectMapper();System.out.println("Using Custom Encoder with ObjectMapper: " + customObjectMapper);return new JacksonEncoder(customObjectMapper);}@BeanLogger.Level feignLoggerLevel() {return Logger.Level.FULL;}
}
注意添加feign.jackson的依赖,选择合适的版本,不匹配可能发生错误。
<dependency><groupId>io.github.openfeign</groupId><artifactId>feign-jackson</artifactId><version>10.4.0</version></dependency>
客户端
@FeignClient(url = "http://localhost:8088/", name = "test-feign-client",configuration = CustomFeignConfig.class)
public interface TestFeignClient {@GetMapping("/votecms/test/testFeign")TestDO testFeign();
}
测试所用的TestDO类为
@Data
public class TestDO {private String name;private Integer age;private Long id;private Date createTime1;private Date createTime2;private LocalDateTime updateTime;
}
测试时所用版本:SpringBoot 2.3.12.RELEASE、SpringCloud 2.2.1.RELEASE