jackson jersey json : 序列化日期从 java 到 json

jackson jersey json : serializing date from java to json

我的 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"

开始日期和结束日期在数据库中的数据类型是日期时间

我在 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 数据库

欢迎提出任何想法。

谢谢 桑吉夫

使用 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;
        }
    }
}