1 package com.fasterxml.jackson.databind.interop; 2 3 import java.time.Instant; 4 import java.time.OffsetDateTime; 5 import java.time.ZoneOffset; 6 7 import com.fasterxml.jackson.databind.*; 8 import com.fasterxml.jackson.databind.exc.InvalidDefinitionException; 9 10 // [databind#2683]: add fallback handling for Java 8 date/time types, to 11 // prevent accidental serialization as POJOs, as well as give more information 12 // on deserialization attempts 13 // 14 // @since 2.12 15 public class DateJava8FallbacksTest extends BaseMapTest 16 { 17 private final ObjectMapper MAPPER = newJsonMapper(); 18 19 private final OffsetDateTime DATETIME_EPOCH = OffsetDateTime.ofInstant(Instant.ofEpochSecond(0L), 20 ZoneOffset.of("Z")); 21 22 // Test to prevent serialization as POJO, without Java 8 date/time module: testPreventSerialization()23 public void testPreventSerialization() throws Exception 24 { 25 try { 26 String json = MAPPER.writerWithDefaultPrettyPrinter() 27 .writeValueAsString(DATETIME_EPOCH); 28 fail("Should not pass, wrote out as\n: "+json); 29 } catch (InvalidDefinitionException e) { 30 verifyException(e, "Java 8 date/time type `java.time.OffsetDateTime` not supported by default"); 31 verifyException(e, "add Module \"com.fasterxml.jackson.datatype:jackson-datatype-jsr310\""); 32 } 33 } 34 testBetterDeserializationError()35 public void testBetterDeserializationError() throws Exception 36 { 37 try { 38 OffsetDateTime result = MAPPER.readValue(" 0 ", OffsetDateTime.class); 39 fail("Not expecting to pass, resulted in: "+result); 40 } catch (InvalidDefinitionException e) { 41 verifyException(e, "Java 8 date/time type `java.time.OffsetDateTime` not supported by default"); 42 verifyException(e, "add Module \"com.fasterxml.jackson.datatype:jackson-datatype-jsr310\""); 43 } 44 } 45 } 46