1.首先定义一个格式化Date 类,这个类要实现JsonSerializer 接口
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* Date 转为json 格式时格式化时间格式
* @author dell
*
*/
public class JsonDateSerializer extends JsonSerializer
private SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String value = "";
if(null !=date){
value = dateFormat.format(date);
}
gen.writeString(value);
}
}
2. 在需要格式化的get方法上加上, @JsonSerialize(using=JsonDateSerializer.class)
如:
@JsonSerialize(using=JsonDateSerializer.class)
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
转化前json结果:
{"resData":{"status":"1","message":"成功","data":{
"pickupInfo":{"pid":"104917","orderid":"17021700912600","prono":"17021702","proname":"boce普??2",
"pickupcode":"46W5S1","pickupnumber":1,"status":"2","userid":"1111110978",
"usercode":"123456789012345678","warehouseid":"天津市河东区仓库街道","createdate":1487260800000,
"pickupdate":null,"username":"提货人信??,"userphone":"15902248761","qualitystan":"","ysendtime":"",
"penaltyrate":0,"keepgoods":"","remark":"","istransferfeeconfirmed":"","isbondconfirmed":""}
}
转化后结果:
{"resData":{"status":"1","message":"成功","data":{
"pickupInfo":{"pid":"104917","orderid":"17021700912600","prono":"17021702","proname":"boce普??2",
"pickupcode":"46W5S1","pickupnumber":1,"status":"2","userid":"1111110978",
"usercode":"123456789012345678","warehouseid":"天津市河东区仓库街道","createdate":2017-02-17 13:58:59,
"pickupdate":null,"username":"提货人信??,"userphone":"15902248761","qualitystan":"","ysendtime":"",
"penaltyrate":0,"keepgoods":"","remark":"","istransferfeeconfirmed":"","isbondconfirmed":""}
}