我的JSON输出如下:
"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"
数据库中startDate和endDate的数据类型是Datetime
我在json中序列化为长整数时得到日期时间。
如何在序列化时将其转换为可读格式 格式MM-dd-yyyy HH:mm:ss
我创建了一个提供程序,但它无法正常工作
这是我的提供者:
@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;
}
}
我正在使用jacskon jersey 2.x,spring mysql数据库
任何想法都表示赞赏。
感谢 Sanjeev
答案 0 :(得分:2)
使用jackson 2.4(如何配置ObjectMapper的细微差别)你有正确的配置(见下文)
您确定正在使用提供商中配置的对象映射器吗?
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;
}
}
}