Reputation: 111
my JSON output looks like:
"company":{"companyId": 0, "companyName": "OnTarget Technologies", "companyTypeId": 0, "address": null,…},
"projectParentId": 24,
"projectAddress":{"addressId": 26, "address1": "4750 59th street", "address2": "Apt 9C", "city": "Woodside",…},
"taskList":[{"projectTaskId": 9, "title": "Installation of Lights", "description": "Installation of lights",…],
"projects": null,
"startDate": 1424322000000,
"endDate": 1427515200000,
"projectImagePath": null
},
{"projectId": 26, "projectName"
the data type in database for startDate and endDate is Datetime
i get the datetime when serialized in json as a long integer.
how do i convert it to a readable format while serializing like in a format MM-dd-yyyy HH:mm:ss
I created a provider but its not working
here's my provider:
@Component
@Provider
public class MyObjectMapper implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public MyObjectMapper() {
this.mapper = createObjectMapper();
}
private static ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, true);
mapper.setDateFormat(new SimpleDateFormat("MM-dd-yyyy HH:mm:ss"));
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
return mapper;
}
@Override
public ObjectMapper getContext(Class<?> aClass) {
return this.mapper;
}
}
I am using jacskon jersey 2.x, spring mysql database
any idea is appreciated.
thanks Sanjeev
Upvotes: 3
Views: 2714
Reputation: 5222
Using jackson 2.4 (so slight difference in how ObjectMapper is configured) you have the correct config (see below)
Are you sure that your object mapper as configured in your provider is being used?
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
public class FooTest {
@Test
public void foo() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
mapper.setDateFormat(new SimpleDateFormat("MM-dd-yyyy HH:mm:ss"));
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
final String output = mapper.writeValueAsString(new Bar(new Date(10000000L)));
assertThat(output, containsString("01-01-1970 03:46:40"));
}
private static class Bar {
@JsonProperty("date")
private Date date;
public Bar() {
}
public Bar(Date date) {
this.date = date;
}
}
}
Upvotes: 2