Java JSON library Jackson Date Date Json 시리얼라이즈/디씨리얼라이즈 

Jackson Date

 

 

1. Overview

 

In this tutorial, we'll serialize dates with Jackson. We'll start by serializing a simple java.util.Date, then Joda-Time as well as the Java 8 DateTime.

2. Serialize Date to Timestamp

 

First – let's see how to serialize a simple java.util.Date with Jackson.

In the following example – we will serialize an instance of “Event” which has a Date field “eventDate“:

@Test
public void whenSerializingDateWithJackson_thenSerializedToTimestamp()
  throws JsonProcessingException, ParseException {
 
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));

    Date date = df.parse("01-01-1970 01:00");
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValueAsString(event);
}

What's important here is that Jackson will serialize the Date to a timestamp format by default (number of milliseconds since January 1st, 1970, UTC).

The actual output of the “event” serialization is:

{
   "name":"party",
   "eventDate":3600000
}

3. Serialize Date to ISO-8601

 

Serializing to this terse timestamp format is not optimal. Let's now serialize the Date to the ISO-8601 format:

@Test
public void whenSerializingDateToISO8601_thenSerializedToText()
  throws JsonProcessingException, ParseException {
 
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));

    String toParse = "01-01-1970 02:30";
    Date date = df.parse(toParse);
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    // StdDateFormat is ISO8601 since jackson 2.9
    mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));
    String result = mapper.writeValueAsString(event);
    assertThat(result, containsString("1970-01-01T02:30:00.000+00:00"));
}

Note how the representation of the date is now much more readable.

4. Configure ObjectMapper DateFormat

 

The previous solutions still lack the full flexibility of choosing the exact format to represent the java.util.Date instances.

Let's now take a look at a configuration that will allow us to set our formats for representing dates:

@Test
public void whenSettingObjectMapperDateFormat_thenCorrect()
  throws JsonProcessingException, ParseException {
 
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");

    String toParse = "20-12-2014 02:30";
    Date date = df.parse(toParse);
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(df);

    String result = mapper.writeValueAsString(event);
    assertThat(result, containsString(toParse));
}
Freestar

Note that, even though we're now more flexible regarding the date format – we're still using a global configuration at the level of the entire ObjectMapper.

5. Use @JsonFormat to Format Date

 

Next, let's take a look at the @JsonFormat annotation to control the date format on individual classes instead of globally, for the entire application:

public class Event {
    public String name;

    @JsonFormat
      (shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
    public Date eventDate;
}

Now – let's test it:

@Test
public void whenUsingJsonFormatAnnotationToFormatDate_thenCorrect()
  throws JsonProcessingException, ParseException {
 
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));

    String toParse = "20-12-2014 02:30:00";
    Date date = df.parse(toParse);
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    String result = mapper.writeValueAsString(event);
    assertThat(result, containsString(toParse));
}

6. Custom Date Serializer

 

Next – to get full control over the output, we'll leverage a custom serializer for Dates:

public class CustomDateSerializer extends StdSerializer<Date> {
 
    private SimpleDateFormat formatter 
      = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

    public CustomDateSerializer() {
        this(null);
    }

    public CustomDateSerializer(Class t) {
        super(t);
    }
    
    @Override
    public void serialize (Date value, JsonGenerator gen, SerializerProvider arg2)
      throws IOException, JsonProcessingException {
        gen.writeString(formatter.format(value));
    }
}

Next – let's use it as the serializer of our “eventDate” field:

public class Event {
    public String name;

    @JsonSerialize(using = CustomDateSerializer.class)
    public Date eventDate;
}

Finally – let's test it:

@Test
public void whenUsingCustomDateSerializer_thenCorrect()
  throws JsonProcessingException, ParseException {
 
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

    String toParse = "20-12-2014 02:30:00";
    Date date = df.parse(toParse);
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    String result = mapper.writeValueAsString(event);
    assertThat(result, containsString(toParse));
}

Further reading:

How To Serialize and Deserialize Enums with Jackson

How to serialize and deserialize an Enum as a JSON Object using Jackson 2.

Jackson – Custom Serializer

Control your JSON output with Jackson 2 by using a Custom Serializer.

Getting Started with Custom Deserialization in Jackson

Use Jackson to map custom JSON to any java entity graph with full control over the deserialization process.

7. Serialize Joda-Time With Jackson

 

Dates aren't always an instance of java.util.Date; actually – they're more and more represented by some other class – and a common one is, of course, the DateTime implementation from the Joda-Time library.

Let's see how we can serialize DateTime with Jackson.

We'll make use of the jackson-datatype-joda module for out-of-the-box Joda-Time support:

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-joda</artifactId>
  <version>2.9.7</version>
</dependency>
Freestar

And now we can simply register the JodaModule and be done:

@Test
public void whenSerializingJodaTime_thenCorrect() 
  throws JsonProcessingException {
    DateTime date = new DateTime(2014, 12, 20, 2, 30, 
      DateTimeZone.forID("Europe/London"));

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    String result = mapper.writeValueAsString(date);
    assertThat(result, containsString("2014-12-20T02:30:00.000Z"));
}

8. Serialize Joda DateTime With Custom Serializer

 

If we don't want the extra Joda-Time Jackson dependency – we can also make use of a custom serializer (similar to the earlier examples) to get DateTime instances serialized cleanly:

public class CustomDateTimeSerializer extends StdSerializer<DateTime> {

    private static DateTimeFormatter formatter = 
      DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");

    public CustomDateTimeSerializer() {
        this(null);
    }

     public CustomDateTimeSerializer(Class<DateTime> t) {
         super(t);
     }
    
    @Override
    public void serialize
      (DateTime value, JsonGenerator gen, SerializerProvider arg2)
      throws IOException, JsonProcessingException {
        gen.writeString(formatter.print(value));
    }
}

Next – let's use it as our property “eventDate” serializer:

public class Event {
    public String name;

    @JsonSerialize(using = CustomDateTimeSerializer.class)
    public DateTime eventDate;
}

Finally – let's put everything together and test it:

@Test
public void whenSerializingJodaTimeWithJackson_thenCorrect() 
  throws JsonProcessingException {
 
    DateTime date = new DateTime(2014, 12, 20, 2, 30);
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    String result = mapper.writeValueAsString(event);
    assertThat(result, containsString("2014-12-20 02:30"));
}

9. Serialize Java 8 Date With Jackson

 

Next – let's see how to serialize Java 8 DateTime – in this example, LocalDateTime – using Jackson. We can make use of the jackson-datatype-jsr310 module:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.9.7</version>
</dependency>

Now, all we need to do is register the JavaTimeModule (JSR310Module is deprecated) and Jackson will take care of the rest:

@Test
public void whenSerializingJava8Date_thenCorrect()
  throws JsonProcessingException {
    LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30);

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    String result = mapper.writeValueAsString(date);
    assertThat(result, containsString("2014-12-20T02:30"));
}

10. Serialize Java 8 Date Without Any Extra Dependency

 

If you don't want the extra dependency, you can always use a custom serializer to write out the Java 8 DateTime to JSON:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

public class CustomLocalDateTimeSerializer 
  extends StdSerializer<LocalDateTime> {

    private static DateTimeFormatter formatter = 
      DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    public CustomLocalDateTimeSerializer() {
        this(null);
    }
 
    public CustomLocalDateTimeSerializer(Class<LocalDateTime> t) {
        super(t);
    }
    
    @Override
    public void serialize(
      LocalDateTime value,
      JsonGenerator gen,
      SerializerProvider arg2)
      throws IOException, JsonProcessingException {
 
        gen.writeString(formatter.format(value));
    }
}

Next – let's use the serializer for our “eventDate” field:

public class Event {
    public String name;

    @JsonSerialize(using = CustomLocalDateTimeSerializer.class)
    public LocalDateTime eventDate;
}

Now – let's test it:

@Test
public void whenSerializingJava8DateWithCustomSerializer_thenCorrect()
  throws JsonProcessingException {
 
    LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30);
    Event event = new Event("party", date);

    ObjectMapper mapper = new ObjectMapper();
    String result = mapper.writeValueAsString(event);
    assertThat(result, containsString("2014-12-20 02:30"));
}

11. Deserialize Date

 
Freestar

Next – let's see how to deserialize a Date with Jackson. In the following example – we deserialize an “Event” instance containing a date:

@Test
public void whenDeserializingDateWithJackson_thenCorrect()
  throws JsonProcessingException, IOException {
 
    String json = "{"name":"party","eventDate":"20-12-2014 02:30:00"}";

    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(df);

    Event event = mapper.readerFor(Event.class).readValue(json);
    assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
}

12. Deserialize Joda ZonedDateTime With Time Zone PreservedIn its default configuration, Jackson adjusts the time zone of a Joda ZonedDateTime to the time zone of the local context. As, by default, the time zone of the local context is not set and has to be configured manually, Jackson adjusts the time zone to GMT:

@Test
public void whenDeserialisingZonedDateTimeWithDefaults_thenNotCorrect()
  throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
    String converted = objectMapper.writeValueAsString(now);

    ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
    System.out.println("serialized: " + now);
    System.out.println("restored: " + restored);
    assertThat(now, is(restored));
}

This test case will fail with output:

serialized: 2017-08-14T13:52:22.071+02:00[Europe/Berlin]
restored: 2017-08-14T11:52:22.071Z[UTC]

Fortunately, there is a quick and simple fix for this odd default-behavior: we just have to tell Jackson, not to adjust the time zone.

This can be done by adding the below line of code to the above test case:

objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

Note that, to preserve time zone we also have to disable the default behavior of serializing the date to the timestamp.

13. Custom Date Deserializer

 

Let's also see how to use a custom Date deserializer; we'll write a custom deserializer for the property “eventDate“:

public class CustomDateDeserializer extends StdDeserializer<Date> {

    private SimpleDateFormat formatter = 
      new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

    public CustomDateDeserializer() {
        this(null);
    }

    public CustomDateDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Date deserialize(JsonParser jsonparser, DeserializationContext context)
      throws IOException, JsonProcessingException {
        String date = jsonparser.getText();
        try {
            return formatter.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

Next – let's use it as the “eventDate” deserializer:

public class Event {
    public String name;

    @JsonDeserialize(using = CustomDateDeserializer.class)
    public Date eventDate;
}

And finally – let's test it:

@Test
public void whenDeserializingDateUsingCustomDeserializer_thenCorrect()
  throws JsonProcessingException, IOException {
 
    String json = "{"name":"party","eventDate":"20-12-2014 02:30:00"}";

    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    ObjectMapper mapper = new ObjectMapper();

    Event event = mapper.readerFor(Event.class).readValue(json);
    assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
}

14. Fixing InvalidDefinitionException

 
Freestar

When creating a LocalDate instance, we may come across an exception:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance
of `java.time.LocalDate`(no Creators, like default construct, exist): no String-argument
constructor/factory method to deserialize from String value ('2014-12-20') at [Source:
(String)"2014-12-20"; line: 1, column: 1]

This problem occurs because JSON doesn't natively have a date format, so represents dates as String.

The String representation of a date isn't the same as an object of type LocalDate in memory, so we need an external deserializer to read that field from a String, and a serializer to render the date to String format.

These methods also apply to LocalDateTime — the only change is to use an equivalent class for LocalDateTime.

14.1. Jackson Dependency

 

Jackson allows us to fix this a couple of ways. First, we have to make sure the jsr310 dependency is in our pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.11.0</version>
</dependency>

14.2. Serialization to Single Date Object

 

In order to be able to handle LocalDate, we need to register the JavaTimeModule with our ObjectMapper.

We also disable the feature WRITE_DATES_AS_TIMESTAMPS in ObjectMapper to prevent Jackson from adding time digits to the JSON output:

@Test
public void whenSerializingJava8DateAndReadingValue_thenCorrect() throws IOException {
    String stringDate = "\"2014-12-20\"";

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    LocalDate result = mapper.readValue(stringDate, LocalDate.class);
    assertThat(result.toString(), containsString("2014-12-20"));
}

Here, we've used Jackson's native support for serializing and deserializing dates.

14.3. Annotation in POJO

 

Another way to deal with that problem is to use the LocalDateDeserializer and JsonFormat annotations at the entity level:

public class EventWithLocalDate {

    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    public LocalDate eventDate;
}
Freestar

The @JsonDeserialize annotation is used to specify a custom deserializer to unmarshal the JSON object. Similarly, @JsonSerialize indicates a custom serializer to use when marshaling the entity.

In addition, the annotation @JsonFormat allows us to specify the format to which we will serialize date values. Therefore, this  POJO can be used to read and write the JSON:

@Test
public void whenSerializingJava8DateAndReadingFromEntity_thenCorrect() throws IOException {
    String json = "{\"name\":\"party\",\"eventDate\":\"20-12-2014\"}";

    ObjectMapper mapper = new ObjectMapper();

    EventWithLocalDate result = mapper.readValue(json, EventWithLocalDate.class);
    assertThat(result.getEventDate().toString(), containsString("2014-12-20"));
}

While this approach takes more work than using the JavaTimeModule defaults, it's a lot more customizable.

15. Conclusion

 

In this extensive Date article, we looked at several ways Jackson can help marshal and unmarshal a date to JSON using a sensible format we have control over.

As always, the examples code can be found over on GitHub.

 

[출처] https://www.baeldung.com/jackson-serialize-dates

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
424 [java, spring] Spring에서 request와 response를 JSON format 으로 한번에 로깅하기 file 졸리운_곰 2021.06.18 178
423 [Spring Boot] 2) Springboot OncePerRequestFilter 와 GenericFilterBean의 차이 file 졸리운_곰 2021.06.18 21
422 [Spring boot] [Spring boot] Spring Boot servlet filter 사용하기 졸리운_곰 2021.06.18 17
421 [SpringBoot] Filter(필터) OncePerRequestFilter간단히 사용하기 file 졸리운_곰 2021.06.18 65
420 [Spring boot] Spring boot 에서 Filter 사용하기 졸리운_곰 2021.06.18 18
419 [Spring Boot] 스프링 부트에 필터를 '조심해서' 사용하는 두 가지 방법 졸리운_곰 2021.06.18 140
418 [Java 자료구조] [Java] 문자열의 첫 글자 제거 졸리운_곰 2021.05.24 404
417 [Java 자료구조] [java] 특정 문자열 사이의 문자열 추출하기, 정규식 졸리운_곰 2021.05.24 1875
416 [Java 자료구조] [JAVA] Java언어로 JSON 생성, 파싱 예제 file 졸리운_곰 2021.05.17 19
415 이클립스에서 java 버전 변경 file 졸리운_곰 2021.04.29 33
414 [Java 자료구조] [Java] Immutable Class (불변 클래스) file 졸리운_곰 2021.03.07 26
413 [Java 자료구조] 불변 객체란? Java Immutable Object file 졸리운_곰 2021.03.07 48
412 [Java 자료구조] [Java] Immutable Object(불변객체) 졸리운_곰 2021.03.07 44
411 [java 자료구조] Oracle + Mybatis 환경에서의 Date 다루기 졸리운_곰 2021.02.25 57
» Java JSON library Jackson Date Date Json 시리얼라이즈/디씨리얼라이즈 file 졸리운_곰 2021.02.25 28
409 [Java, JSON, jackson] Ignoring new fields on JSON objects using Jackson 졸리운_곰 2021.02.19 16
408 [Java] [Jackson] JsonInclude 속성에 대해 알아보자. 졸리운_곰 2021.02.03 592
407 [java] [jackson] Map - JSON간 변환 졸리운_곰 2021.02.02 41
406 [java] [자료구조] Remove null values from json using jackson 졸리운_곰 2021.02.02 78
405 Eclipse RAP Tutorial for Beginners - Workbench Application (OLD) file 졸리운_곰 2021.01.30 66
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED