As @PaulSamsotha pointed out, I need to register the JacksonJsonProvider on the client side too:
ClientConfig cc = new DefaultClientConfig();
cc.getSingletons().add(ShopApplication.newJacksonJsonProvider());
wr = Client.create(cc).resource(Main.BASE_URI.resolve("products"));
which contains the customized solution:
private static JacksonJsonProvider newJacksonJsonProvider() {
ObjectMapper mapper =
new ObjectMapper()
.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule()); // new module, NOT JSR310Module
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.setDateFormat(new StdDateFormat());
return new JacksonJsonProvider(mapper);
}
Answer from Mincong Huang on Stack OverflowAs @PaulSamsotha pointed out, I need to register the JacksonJsonProvider on the client side too:
ClientConfig cc = new DefaultClientConfig();
cc.getSingletons().add(ShopApplication.newJacksonJsonProvider());
wr = Client.create(cc).resource(Main.BASE_URI.resolve("products"));
which contains the customized solution:
private static JacksonJsonProvider newJacksonJsonProvider() {
ObjectMapper mapper =
new ObjectMapper()
.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule()); // new module, NOT JSR310Module
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.setDateFormat(new StdDateFormat());
return new JacksonJsonProvider(mapper);
}
I was able to deserialize a JSON file with a ZonedDateTime with this code.
ObjectMapper objectMapper = new ObjectMapper()
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
objectMapper.registerModule(new JavaTimeModule())
MyObject myObject = objectMapper.readValue(new File("src/test/resources/data/my_object.json"), MyObject.class)
Thanks for those who answered.
With the help of team mate, we discovered that the spring cloud has its own object mapper. And not the ObjectMapper directly. Since this DTO/POJO is to the message from a AWS SNS/SQS.
This should do:
@Bean
public MappingJackson2MessageConverter mappingJackson2MessageConverter(ObjectMapper objectMapper) {
MappingJackson2MessageConverter jacksonMessageConverter = new MappingJackson2MessageConverter();
jacksonMessageConverter.setObjectMapper(objectMapper);
jacksonMessageConverter.setSerializedPayloadClass(String.class);
jacksonMessageConverter.setStrictContentTypeMatch(true);
return jacksonMessageConverter;
}
Use
@JsonFormat(pattern = 'specify pattern here')
ObjectMapper by default tries to create ZonedDateTime object with String in constructor and such thing does not exists. By adding this annotation you will allow it to parse it from String using given format.
You need jackson dependency for this serialization and deserialization.
Add this dependency:
Gradle:
compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.4")
Maven:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
After that, You need to tell Jackson ObjectMapper to use JavaTimeModule. To do that, Autowire ObjectMapper in the main class and register JavaTimeModule to it.
import javax.annotation.PostConstruct;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
@SpringBootApplication
public class MockEmployeeApplication {
@Autowired
private ObjectMapper objectMapper;
public static void main(String[] args) {
SpringApplication.run(MockEmployeeApplication.class, args);
}
@PostConstruct
public void setUp() {
objectMapper.registerModule(new JavaTimeModule());
}
}
After that, Your LocalDate and LocalDateTime should be serialized and deserialized correctly.
Spring Boot 2.2.2 / Gradle:
Gradle (build.gradle):
implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")
Entity (User.class):
LocalDate dateOfBirth;
Code:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
User user = mapper.readValue(json, User.class);
In your pojo you need to set annotation
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
For more details look at the answer for question Spring Data JPA - ZonedDateTime format for json serialization
jackson-datatype-jsr310 is registered by default if on the classpath as stated on Springs own blog Jackson-Modules Spring Blog so no need to register it manually in a new ObjectMapper at all.
This does not work because your input (and your Formatter) do not have time zone information. A simple way is to parse your date as a LocalDate first (without time or time zone information) then create a ZonedDateTime:
public static ZonedDateTime convertirAFecha(String fecha) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse(fecha, formatter);
ZonedDateTime resultado = date.atStartOfDay(ZoneId.systemDefault());
return resultado;
}
This is a bug, see JDK-bug-log. According to that information the problem was solved for Java 9 and Java 8u20. Try to download the latest Java 8 - version. Today on 2014-05-12: There is an early access release 8u20 available.
UPDATE:
Personally I think, since you only have and expect "dd/MM/yyyy" as pattern you should use LocalDate as your primary type as @assylias has already proposed. Regarding your context, it is almost sure a design failure to use ZonedDateTime. What do you want to do with objects of this type? I can only think of specialized timezone calculations as use-case. And you cannot even directly store these ZonedDateTime-objects in a database, so this type is far less useful than many people believe.
What I described as your use-case problem is indeed a new aspect introduced with Java-8 compared with the old GregorianCalendar-class (which is an all-in-one-type). Users have to start thinking about choosing the proper temporal type for their problems and use-cases.
add below annotation over the field LocalDate
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate start;
need to install JsonFormat JsonDeserialize JsonSerialize
private LocalDate dateOfBirth;
@PastOrPresent(message = "must be past time or present")
@Column(name = "date_of_birth", nullable = false, columnDefinition = "DATE")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}