gpt4 book ai didi

java - 更改 Spring Data Rest WebMvc 中的 Jackson 日期格式设置

转载 作者:行者123 更新时间:2023-12-01 22:56:20 26 4
gpt4 key购买 nike

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更改为例如2014年5月1日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);

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

最佳答案

我在 Github 上发布了此修复 - 但它是:

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

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

}

}

关于java - 更改 Spring Data Rest WebMvc 中的 Jackson 日期格式设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23996776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com