001/* 002 * Copyright 2020 Global Biodiversity Information Facility (GBIF) 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.gbif.api.jackson; 017 018import java.io.IOException; 019import java.time.Instant; 020import java.util.Date; 021 022import org.junit.jupiter.api.Test; 023 024import com.fasterxml.jackson.databind.ObjectMapper; 025import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 026import com.fasterxml.jackson.databind.annotation.JsonSerialize; 027 028import static org.junit.jupiter.api.Assertions.assertEquals; 029 030/** 031 * Test {@link Date} serialization using DateSerde. 032 */ 033public class DateDeserTest { 034 035 private static final ObjectMapper MAPPER = new ObjectMapper(); 036 037 @Test 038 public void testBothWays() throws IOException { 039 Date d = Date.from(Instant.parse("1924-03-13T10:11:12.13Z")); 040 041 DateWrapper Date = new DateWrapper(d); 042 String json = MAPPER.writeValueAsString(Date); 043 assertEquals("{\"date\":\"1924-03-13T10:11:12\"}", json); 044 assertEquals("1924-03-13T10:11:12Z", MAPPER.readValue(json, DateWrapper.class).date.toInstant().toString()); 045 } 046 047 @Test 048 public void testLegacyDeser() throws IOException { 049 String json = "{\"date\":\"1924-03-13T10:11:12.130+0000\"}"; 050 assertEquals("1924-03-13T10:11:12.130Z", MAPPER.readValue(json, DateWrapper.class).date.toInstant().toString()); 051 } 052 053 public static class DateWrapper { 054 @JsonSerialize(using = DateSerde.NoTimezoneDateJsonSerializer.class) 055 @JsonDeserialize(using = DateSerde.FlexibleDateJsonDeserializer.class) 056 public Date date; 057 058 public DateWrapper() {} 059 060 public DateWrapper(Date date){ 061 this.date = date; 062 } 063 } 064}