gpt4 book ai didi

java - 如果日期不包含时区,则从 FormDataBodyPart/Jackson 输入 json 时抛出异常

转载 作者:行者123 更新时间:2023-11-30 01:46:09 25 4
gpt4 key购买 nike

假设我在使用 Jersey 框架时有一个带有附件的 POST 请求。从我的 Jersey 端点,我得到一个 FormDataBodyPart,其中包含 json 字符串:

    {   
"aField": "aValue",
"aSecondField":"anotherValue",
"collectionDate" : {
"firstDate" : "2019-07-15",
"secondDate" : "2019-07-15T00:00:00.000Z"
}
}

当我将该 json 反序列化为 Java 对象时,firstDate 字段反射(reflect)另一个日期,因为它没有时区 (2019-07-14T22:00:00.000Z)。

formDataBodyPartData.setMediaType(MediaType.APPLICATION_JSON_TYPE);
EntityExample entityExample = formDataBodyPartData.getValueAs(EntityExample.class);

所以我想强制用户在每个日期中添加时区信息。是否可以 ? (我也可以有一个基于 Jackson 的解决方案)。

提前致谢。

编辑:

collectionDate 类具有以下架构,不幸的是我无法更改它。

public class CollectionDate{
private java.util.Date firstDate;
private java.util.Date secondDate;
....
}

所以我想要一个解决方案,以便在使用该行时限制 json 字符串的解码:

formDataBodyPartData.getValueAs(..)

我也可以有一个基于 jackson 的解决方案,例如:

EntityExample entityExample = objectMapper.readValue(value, EntityExample.class);

提前致谢。

最佳答案

您可以使用 OffsetDateTime 用于映射 firstDatesecondDate特性。当输入与 DateTimeFormatter.ISO_OFFSET_DATE_TIME 不匹配时,反序列化将失败图案:

@Data
public class CollectionDate {
private OffsetDateTime firstDate;
private OffsetDateTime secondDate;
}

要使用 Jackson 作为 JAX-RS 的 JSON 提供程序,您必须添加 jackson-jaxrs-json-provider 作为依赖的工件。

您还需要注册 JavaTimeModule ObjectMapper 。它可以在 ContextResolver<T> 中完成:

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {

private final ObjectMapper mapper;

public ObjectMapperContextResolver() {
this.mapper = createObjectMapper();
}

@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}

private ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
return mapper;
}
}

关于java - 如果日期不包含时区,则从 FormDataBodyPart/Jackson 输入 json 时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57868072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com