Aayush Chachan
Aayush Chachan

Reputation: 27

How to use JacksonJSONProvider ObjectMapper() class in Java?

I want to deserialize the OffsetDateTime JSON object into ISO8601 format

I have generated the JacksonJSONProvider classes through swagger-code-gen but I am not able to figure out how to use class...

Here is the Code Of The Class


@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);
    }
}

Actual result

"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

Expected Result

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

Upvotes: 1

Views: 2163

Answers (1)

Michael Gantman
Michael Gantman

Reputation: 7790

Your Expected result

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

is not in JSON format at all, so a JSON formatter will not help you. To parse a OffsetDateTime into your desired format you need to use DateTimeFormatter class. However, if you have a class that has a member of type OffsetDateTime and you want to serialize your entire class to JSON then here is the link to the question that gives you the right answer: Spring Data JPA - ZonedDateTime format for json serialization . Basically the solution will look like

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

Upvotes: 1

Related Questions