gpt4 book ai didi

java - jackson 日期格式问题 : java bean to JSON string conversion

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:20:16 27 4
gpt4 key购买 nike

我正在使用 Jackson 2.7.4 版本将 java bean 转换为 JSON 字符串。这样做时,我面临日期格式问题。正在使用Java 1.7版本。

bean 类:

public class BaseBean {

private java.util.Date fromDate;

public Date getFromDate() {
return fromDate;
}

public void setFromDate(Date fromDate) {
this.fromDate = fromDate;
}
}

低于日期格式

{"fromDate":1465370289436}

这不是我要求的。然后我配置下面的代码

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS , false);
jsonInString = objectMapper.writeValueAsString(objJava);

然后我得到 below date JSON 格式:

{"fromDate":"2016-06-08T07:47:06.636+0000"}

预计日期格式:

{"fromDate":{"date":8,"day":3,"hours":12,"minutes":48,"month":5,"seconds":9,"time":1465370289436,"timezoneOffset":-330,"year":116}}

是否有任何配置来处理它并获取 JSON 字符串中的预期日期格式。

最佳答案

JSON 日期序列化器:

public class CustomDateSerializer extends JsonSerializer<Date> {

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

// below methods of Date object is deprecated - consider this as sample example
int idate = date.getDate();
int day = date.getDay();
int hours = date.getHours();
int minutes = date.getMinutes();
int month = date.getMonth();
int seconds = date.getSeconds();
long time = date.getTime();
int timezoneOffset = date.getTimezoneOffset();
int year = date.getYear();

jgen.writeStartObject();

jgen.writeNumberField("date", idate);
jgen.writeNumberField("day", day);
jgen.writeNumberField("hours", hours);
jgen.writeNumberField("minutes", minutes);
jgen.writeNumberField("month", month);
jgen.writeNumberField("seconds", seconds);
jgen.writeNumberField("time", time);
jgen.writeNumberField("timezoneOffset", timezoneOffset);
jgen.writeNumberField("year", year);

jgen.writeEndObject();
}

@Override
public Class<Date> handledType() {
return Date.class;
}

在 SimpleModule 中设置序列化器:

ObjectMapper objectMapper = new ObjectMapper();
String jsonInString = "";
try {
SimpleModule myModule = new SimpleModule();

myModule.addSerializer(Date.class, new CustomDateSerializer());
objectMapper.registerModule(myModule);
jsonInString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(objJava);
} catch (JsonProcessingException e1) {
e1.printStackTrace();
}

希望这会有所帮助!

关于java - jackson 日期格式问题 : java bean to JSON string conversion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37696402/

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