ZonedDateTime无法从JSON中解析,但可以使用格式化程序进行解析

55ooxyrt  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(62)

我有一个通过JSON输入的日期字符串:“29-OCT-21 12.00.00.000000000 AM UTC”。我想保存它作为ZonedDateTime数据类型。
我在模型中设置了如下属性:

@JsonProperty("createdTs")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MMM-yy hh.mm.ss.SSSSSSSSS a z", with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
    private ZonedDateTime createdTs;

字符串
我得到一个错误:

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.ZonedDateTime` from String "29-OCT-21 12.00.00.000000000 AM UTC": Failed to deserialize java.time.ZonedDateTime: (java.time.format.DateTimeParseException) Text '29-OCT-21 12.00.00.000000000 AM UTC' could not be parsed


我不知道哪里出了问题。在测试用例中,模式在格式化程序中工作得很好,就像这样:

DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("dd-MMM-yy hh.mm.ss.SSSSSSSSS a z").toFormatter(
        Locale.getDefault());
    locationPayload.setcreatedTs(ZonedDateTime.parse("29-OCT-21 12.00.00.000000000 AM UTC", formatter));

rjjhvcjd

rjjhvcjd1#

此问题与JsonFormat无法处理JSON字符串中的复杂日期-时间格式有关。要解决此问题,您可以为ZonedDateTime类型创建自定义验证程序。
下面是一个示例:

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.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class ZonedDateTimeDeserializer extends JsonDeserializer<ZonedDateTime> {

    private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("dd-MMM-yy hh.mm.ss.SSSSSSSSS a z")
            .toFormatter();

    @Override
    public ZonedDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String dateString = jsonParser.getText();
        return ZonedDateTime.parse(dateString, FORMATTER);
    }
}

字符串
你的财产

public class Test {

    @JsonProperty("createdTs")
    @JsonDeserialize(using = ZonedDateTimeDeserializer.class)
    private ZonedDateTime createdTs;
//Getter & Settere
}


测试

public static void main(String[] args) throws JsonProcessingException {
        String s = """
                {
                "createdTs": "29-OCT-21 12.00.00.000000000 AM UTC"
                }
                """;

        Test t = JsonMapper.builder().findAndAddModules().build().readValue(s, Test.class);

        System.out.println(t);
    }


输出Test(createdTs=2021-10-29T00:00Z[UTC])
试试看,然后告诉我

相关问题