如何在Java中使用JacksonJSONProvider ObjectMapper()类?

时间:2019-06-17 05:02:10

标签: java java-8 jackson jax-rs jackson-databind

我想将deserialize JSON对象OffsetDateTime转换为ISO8601格式

我已经通过JacksonJSONProvider生成了swagger-code-gen类,但是我不知道如何使用类...

这是班上的代码


@Provider
@Produces({MediaType.APPLICATION_JSON})
public class JacksonJsonProvider extends JacksonJaxbJsonProvider {

    public JacksonJsonProvider() {

        ObjectMapper objectMapper = new ObjectMapper()
                .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .registerModule(new JavaTimeModule())
                .setDateFormat(new RFC3339DateFormat());

        setMapper(objectMapper);
    }
}

实际结果

"offset": {
            "totalSeconds": 19800,
            "id": "+05:30",
            "rules": {
                "transitions": [],
                "transitionRules": [],
                "fixedOffset": true
            }
        },
        "year": 2006,
        "month": "NOVEMBER",
        "monthValue": 11,
        "dayOfMonth": 8,
        "hour": 15,
        "minute": 57,
        "second": 0,
        "nano": 0,
        "dayOfWeek": "WEDNESDAY",
        "dayOfYear": 312

预期结果

"2006-11-08T21:27:00.000+0000"

1 个答案:

答案 0 :(得分:1)

您的预期结果

  

“ 2006-11-08T21:27:00.000 + 0000”

根本不是JSON格式,因此JSON格式器将无济于事。要将OffsetDateTime解析为所需格式,您需要使用DateTimeFormatter类。但是,如果您的类的成员类型为OffsetDateTime,并且您想将整个类序列化为JSON,那么这里的问题链接提供了正确的答案:Spring Data JPA - ZonedDateTime format for json serialization 。基本上,解决方案看起来像

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss.SSSZ", locale = "en")
    private OffsetDateTime myTime;