我有一个主要课程:
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class ContentModel implements Serializable {
@JsonProperty("serviceData")
private ServiceData serviceData;
}
和嵌套类:
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class ServiceData implements Serializable {
@JsonProperty ("dateTimeMessageSend")
private LocalDateTime dateTimeMessageSend;
}
我正在尝试通过使用自定义反序列化器来反序列化它:
public class LocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {
private static final long serialVersionUID = 1L;
protected LocalDateTimeDeserializer() {
super(LocalDateTime.class);
}
@Override
public LocalDateTime deserialize(final JsonParser jp, final DeserializationContext ctxt)
throws IOException {
return LocalDateTime.parse(jp.readValueAs(String.class));
}
}
这就是我如何配置我的 objectMapper:
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
this.objectMapper.registerModule(javaTimeModule);
this.objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
this.objectMapper.registerModule(new Jdk8Module());
this.objectMapper.findAndRegisterModules();
应用程序在以下 json 之外接收:
{
"serviceData": {
"dateTimeMessageSend": {
"month": "APRIL",
"dayOfYear": 109,
"dayOfWeek": "MONDAY",
"nano": 183251000,
"year": 2021,
"monthValue": 4,
"dayOfMonth": 19,
"hour": 14,
"minute": 52,
"second": 44,
"chronology": {
"calendarType": "iso8601",
"id": "ISO"
}
},
}
}
在 LocalDateTime 反序列化时,我收到异常:
MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token
我想,杰克逊将“dateTimeMessageSend”识别为一个对象并且无法将其解析为字符串。
解决问题的方法是什么?
- 修改源 json,例如将 LocalDateFormat 更改为 String。(什么是不受欢迎的)
- 进一步定制 objectMapper 或/和 LocalDateTimeDeserializer