Jackson Redisson反序列化問題

临渊不羡渔發表於2024-03-12

異常資訊

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `java.util.concurrent.atomic.AtomicInteger` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (0)

原因

類裡面有個 AtomicInteger 型別變數, jackson 找不到改類的透過 Number value 0 的反序列化方法。

解決方案

手動新增一個反序列化配置,

// 以下程式碼直接在時間序列化 module 裡面新增 AtomicInteger 的反序列化配置。
static class AtomicIntegerDeserializer extends JsonDeserializer<AtomicInteger> {

	@Override
	public AtomicInteger deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
		return new AtomicInteger(p.getValueAsInt());
	}
}

@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
	JavaTimeModule module = new JavaTimeModule();
	module.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_PATTERN)));
	module.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(TIME_PATTERN)));
	module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_PATTERN)));
	module.addDeserializer(AtomicInteger.class, new AtomicIntegerDeserializer());
	return builder -> {
		builder.simpleDateFormat(DATE_TIME_PATTERN);
		builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_PATTERN)));
		builder.serializers(new LocalTimeSerializer(DateTimeFormatter.ofPattern(TIME_PATTERN)));
		builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_PATTERN)));
		builder.modules(module);
	};
}

極簡生效程式碼

ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(AtomicInteger.class, new AtomicIntegerDeserializer());
objectMapper.registerModule(module);

相關文章