在spring data rest webmvc中更改Jackson日期格式设置

时间:2014-06-02 14:20:20

标签: java spring spring-mvc jackson lightadmin

Lightadmin用于时间戳字段,例如:

@Temporal(TemporalType.TIMESTAMP)
@Column(name="started_at")
Date startedAt;

不对它们进行格式化,而是将它们显示为自纪元以来的毫秒数,例如1398940456150

当您输入Lightadmin编辑页面时,例如http://localhost:8080/admin/domain/user/1/edit实际填充表单的值在另一个请求中收到 - http://localhost:8080/admin/rest/user/1/unit/formView?_=1401699535260,它返回JSON:

...
"startedAt" : {
    "name" : "startedAt",
    "title" : "started at timestamp",
    "value" : 1398940456150,
    "type" : "DATE",
    "persistable" : true,
    "primaryKey" : false
}
...

任务是将1398940456150更改为例如01.05.2014 10:34:16

根据我的调查,org.lightadmin.core.rest.DynamicRepositoryRestController.entity()是此类请求的入口点,负责生成JSON的代码位于:org.springframework.data.rest.webmvc.RepositoryAwareMappingHttpMessageConverter.writeInternal()

try {
  mapper.writeValue(jsonGenerator, object);
} catch(IOException ex) {
  throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
}

mapperorg.codehaus.jackson.map.ObjectMapper.ObjectMapper的实例,使用默认值初始化。如果可以添加这两行:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mapper.getSerializationConfig().setDateFormat(df);

它会完成这项工作,问题是如何做到这一点?

3 个答案:

答案 0 :(得分:1)

我不清楚这个data-rest-webmvc但你可以尝试注册一个cusotm转换器,如下所示:

@Component
public class DateConverter implements Converter<String, Date> {


    @Override
    public Date convert(String source) {
        return // do the conversion
    }
}

并注册如下:

 <bean id="conversionService"
          class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.myapp.DateConverter"/>
            </set>
        </property>
    </bean>

答案 1 :(得分:1)

我在Github上发布了此修复程序 - 但现在是:

我通过更改lightadmin代码中的类DomainTypeResourceModule来修复此问题。这是该类的更新源代码。可能有更好的方法来解决它 - 但这是最​​不具侵入性的方式,它涵盖了序列化和反序列化。

package org.lightadmin.core.rest;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.deser.std.StdDeserializer;
import org.codehaus.jackson.map.module.SimpleDeserializers;
import org.codehaus.jackson.map.module.SimpleModule;
import org.codehaus.jackson.map.module.SimpleSerializers;
import org.codehaus.jackson.map.ser.std.SerializerBase;
import org.springframework.hateoas.Resource;

public class DomainTypeResourceModule extends SimpleModule {

    private final DomainTypeToResourceConverter domainTypeToResourceConverter;

    public DomainTypeResourceModule(final DomainTypeToResourceConverter domainTypeToResourceConverter) {
        super("DomainTypeResourceModule", Version.unknownVersion());

        this.domainTypeToResourceConverter = domainTypeToResourceConverter;
    }

    @Override
    public void setupModule(final SetupContext context) {
        SimpleSerializers serializers = new SimpleSerializers();
        serializers.addSerializer(DomainTypeResource.class, new DomainTypeResourceSerializer());
        serializers.addSerializer(Date.class, new JsonDateSerializer());

        SimpleDeserializers deserializers = new SimpleDeserializers();
        deserializers.addDeserializer(Date.class, new JsonDateDeserializer());

        context.addDeserializers(deserializers);
        context.addSerializers(serializers);
    }

    private class DomainTypeResourceSerializer extends SerializerBase<DomainTypeResource> {

        protected DomainTypeResourceSerializer() {
            super(DomainTypeResource.class);
        }

        @Override
        public void serialize(DomainTypeResource value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            if (null == value) {
                provider.defaultSerializeNull(jgen);
                return;
            }

            final Resource resource = domainTypeToResourceConverter.convert(value.getResource(), value.getConfigurationUnitType(), value.getFieldMetadatas());

            jgen.writeObject(resource);
        }
    }

    private class JsonDateSerializer extends SerializerBase<Date> {

        protected JsonDateSerializer() {
            super(Date.class);
        }

        @Override
        public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException, JsonProcessingException {

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = date == null ? "" : dateFormat.format(date);

            gen.writeString(formattedDate);
        }

    }

    private class JsonDateDeserializer extends StdDeserializer<Date> {

        protected JsonDateDeserializer() {
            super(Date.class);
        }

        @Override
        public Date deserialize(JsonParser json, DeserializationContext context) throws IOException, JsonProcessingException {

            try {
                if(json.getText() != null && !"".equals(json.getText().trim())) {
                    try {
                        return new Date(Long.parseLong(json.getText()));
                    }
                    catch(NumberFormatException nex){
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        return dateFormat.parse(json.getText());
                    }
                }
                else return null;
            }
            catch (ParseException e){
                return null;
            }
        }

    }

}

答案 2 :(得分:1)

最新的LightAdmin 1.1.0.BUILD-SNAPSHOT版本包含扩展数据类型支持和主要错误修复,包括与时间戳相关的内容。

请检查出来,随时问我任何问题。