I am working with Jackson
version 2.8.7
I have a Person
object that is printed in the following way:
object: Persona [id=087, nombre=Leonardo, apellido=Jordan, fecha=Sun Jul 05 00:00:00 PET 1981]
Observe the date part Sun Jul 05 00:00:00 PET 1981
I did a research from these two valuable posts about how serialize an object (entity) and a Date object into JSON format:
- Converting Java objects to JSON with Jackson
- How to make JsonGenerator pretty-print Date and DateTime values?
When I use:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getSerializationConfig().with(dateFormat);
ObjectWriter ow = objectMapper.writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
Observe two things:
objectMapper.getSerializationConfig().with(dateFormat);
writer()
I always get:
json: {
"id" : "087",
"nombre" : "Leonardo",
"apellido" : "Jordan",
"fecha" : 363157200000
}
Observe the 363157200000
value and without quotes.
Therefore it did not work.
But If use:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
ObjectMapper objectMapper = new ObjectMapper();
//objectMapper.getSerializationConfig().with(dateFormat);
ObjectWriter ow = objectMapper.writer(dateFormat).withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
Observe two things:
//objectMapper.getSerializationConfig().with(dateFormat);
commentedwriter(dateFormat)
the argument
I always get:
json: {
"id" : "087",
"nombre" : "Leonardo",
"apellido" : "Jordan",
"fecha" : "1981-07-05"
}
Now works.
- Why the first approach did not work?
- What is the correct configuration for the first approach to get the expected behaviour?
I am more interested in the first approach in case I need apply more features through the getSerializationConfig().with(...)
methods.