我正在使用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);
然后我在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字符串中获得预期的日期格式。
答案 0 :(得分:4)
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();
}
希望这会有所帮助!
答案 1 :(得分:0)
您可以在课程中添加方法以获取:
例如
private DateFormat hoursDF = new SimpleDateFormat("HH");
public String getHours() {
return hoursDF.format(fromDate);
}
答案 2 :(得分:0)
使用JsonSerialize进行批注。可以覆盖JsonSerializer的serialize方法。