为什么杰克逊格式的日期是yyyy-MM-dd而不是时间戳?

时间:2015-06-21 10:40:25

标签: json spring maven spring-mvc jackson

我的第一个春季项目有休息服务。 只有一个问题我无法解决自己。我的#34;得到" request以这种方式给出对象的日期值:

{"id":6,"type":"Trainer","changed":"2015-06-20","created":"2015-06-19"}

但我希望它采用时间戳格式,因为我认为是默认格式。

我的PUT请求中的输入日期将按照预期从时间戳格式进行解析。

我正在使用springframework 4.1.6.RELEASE和fasterxml.jackson 2.5.4 使用这些弹簧工件:spring-context,spring-webmvc,spring-jdbc

和这些fastxml工件:jackson-core,jackson-databind

这是我的控制器方法:

@Override
@RequestMapping(value="/{id}", method=RequestMethod.GET)
@ResponseBody
public T getObject(@PathVariable("id") long id) {
    T obj = dao.getById(id);
    logger.debug("GET " + getClass().getSimpleName() + "." + id + ": " + obj);
    return obj;
}

我的web.xml:

<?xml 

    version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        version="2.5">
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
            /WEB-INF/spring/root-context.xml
            </param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <servlet>
            <servlet-name>appServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>
                    /WEB-INF/spring/appServlet/servlet-context.xml
                    classpath:Beans.xml
                </param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>appServlet</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    </web-app>

servlet的context.xml中:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="de.kreth.clubhelperbackend" />

    <mvc:annotation-driven />

    <mvc:resources mapping="/resources/**" location="/resources/" />

    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="2" />
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

和我的Beans.xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/clubhelperbackend" />
        <property name="username" value="markus" />
        <property name="password" value="0773" />
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg ref="dataSource" />
    </bean>

    <bean id="sqlForDialect" class="de.kreth.clubhelperbackend.SqlForMysql">
        <constructor-arg ref="jdbcTemplate" />
    </bean>

    <bean id="personDao" class="de.kreth.clubhelperbackend.dao.PersonDao">
        <property name="sqlDialect" ref="sqlForDialect" />
        <property name="jdbcTemplate" ref="jdbcTemplate" />
    </bean>

    <bean id="dbcheckAspect" class="de.kreth.clubhelperbackend.aspects.MysqlDbCheckAspect">
        <constructor-arg ref="dataSource" />
    </bean>

<!--    <bean id="logger" class="de.kreth.clubhelperbackend.aspects.LoggerAspect" /> -->

    <aop:aspectj-autoproxy>
        <aop:include name="dbcheckAspect" />
<!--        <aop:include name="logger"/> -->
    </aop:aspectj-autoproxy>

</beans>

那么,我怎样才能将json日期输出作为时间戳获得?

请注意,我不想更改从其他项目生成的数据类(getter)。

---编辑: 人物模型:

public class Person implements java.io.Serializable, Data  {

    private static final long serialVersionUID = -2810735258874241724L;
    private Long id;
    private String type;

    /** Not-null value. */
    private java.util.Date changed;
    /** Not-null value. */
    private java.util.Date created;

    public Person() {
    }

    public Person(Long id) {
        this.id = id;
    }

    public Person(Long id, String type,java.util.Date changed, java.util.Date created) {
        this.id = id;
        this.type = type;
        this.changed = changed;
        this.created = created;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    /** Not-null value. */
    public java.util.Date getChanged() {
        return changed;
    }

    /** Not-null value; ensure this value is available before it is saved to the database. */
    public void setChanged(java.util.Date changed) {
        this.changed = changed;
    }

    /** Not-null value. */
    public java.util.Date getCreated() {
        return created;
    }

    @Override
    public void setCreated(Date created) {
        this.created = created;
    }
}

日期界面:

package de.kreth.clubhelperbackend.pojo;
import java.util.Date;

public interface Data {
    public Long getId() ;
    public void setId(Long id);
    public Date getChanged();
    public void setChanged(Date changed);
    public Date getCreated();
    public void setCreated(Date created);
}

2 个答案:

答案 0 :(得分:0)

According Jackson docs,默认情况下,杰克逊应该以毫秒为单位使用时间戳。

所以我看到两个选择。一个是您的日期格式由日期字段上的@JsonFormat注释强制执行,如@beerbajay在评论中提到的那样。

第二个选项是有人为您的ObjectMapper配置了自定义MappingJacksonHttpMessageConverter。此类示例配置位于this SO answer中。我会尝试在你的应用程序中找到它并与介绍它的队友讨论它为什么需要它。

如果没有配置这样的自定义ObjectMap,它很奇怪,但至少你可以尝试将SerializationConfig.getDateFormat显式配置为WRITE_DATES_AS_TIMESTAMPS为真。

答案 1 :(得分:0)

我认为杰克逊以不同的方式对待java.util.Datejava.sql.Date。虽然后者实际上是前者的一个子类,但杰克逊认为这两个类完全不同。

因此,如果您不希望将值转换为&#39; yyyy-MM-dd&#39;,请确保它不是java.sql.Date对象。

例如:

class Student {
   private java.util.Date birthDate;

   // getter and setter
}

Student san = new Student();

// Then JSON converted to: 'yyyy-MM-dd' format
san.setBirthDate(new java.sql.Date(System.currentTimeMillis()));

// Then JSON converted to: timestamp format or according to @JsonFormat format
san.setBirthDate(new java.util.Date());