概述:
Jackson 对 java.util.Date 的默认序列化是时间戳。我们可以通过ObjectMapper提供的setDateFormat方法去改变其对 java.util.Date 的序列化格式。
public ObjectMapper setDateFormat(DateFormat dateFormat) {
this._deserializationConfig = (DeserializationConfig)this._deserializationConfig.with(dateFormat);
this._serializationConfig = this._serializationConfig.with(dateFormat);
return this;
}
代码示例:
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class JacksonTest {
private final static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
objectMapper.setDateFormat(df);
}
public static void main(String[] args) throws JsonProcessingException {
serialize();
}
public static void serialize() throws JsonProcessingException {
Calendar calendar = Calendar.getInstance();
calendar.set(1989, 4, 15);
Date birthDay = new Date(calendar.getTimeInMillis());
Person person = new Person();
person.setName("iyushu");
person.setBirthDay(birthDay);
System.out.println(objectMapper.writeValueAsString(person));
}
}
import java.util.Date;
public class Person {
private String name;
private Integer age;
private Date birthDay;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthDay() {
return birthDay;
}
public void setBirthDay(Date birthDay) {
this.birthDay = birthDay;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", birthDay=" + birthDay +
'}';
}
}
输出结果:
{"name":"iyushu","birthDay":"1989-05-15"}