SpringBoot@JsonDeserialize⾃定义Json序列化SpringBoot @JsonDeserialize⾃定义Json序列化
1、问题
在项⽬上使⽤SpringBoot为框架,调⽤第三⽅接⼝时,返回的参数Date类型,需要⾃定义进⾏Json序列化,需要进⾏处理,接受数据
2、现象
调⽤第三⽅接⼝,返回参数类型为Date类型,格式如下:
{
"created": "2018-12-27 16:15:25",
"lastupd": "2018-12-27 08:25:48"
}
返回Date类型数据格式为:yyyy-MM-dd HH:mm:ss,Json默认序列化Date类型参数,格式为:yyyy-MM-dd HH:mm:ss.SSS,则需要⾃定义进⾏系列化
3、解决办法
springboot框架的作用
创建接收数据对象,⽣成Get\Set⽅法:,在Set⽅法上,加上@JsonDeserialize注解,如下:
public class TestDto implements Serializable {
/**
* ⽣成时间
*
*/
private Date created;
/**
* LastUpd
*
*/
private Date lastUpd;
public Date getCreated() {
return created;
}
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
public void setCreated(Date created) {
}
public Date getLastUpd() {
return lastUpd;
}
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
public void setLastUpd(Date lastUpd) {
this.lastUpd = lastUpd;
}
}
在进⾏⾃定义序列化时,加上 @JsonDeserialize(using = CustomJsonDateDeserializer.class)注解,
其中@JsonDeserialize,表⽰告诉SpringBoot,当前属性进⾏⾃定义系列化,则SpringBoot进⾏序列化时,将会跳过这个参数
CustomJsonDateDeserializer.class为⾃定义序列化对象,如下:
st;
import com.JsonParser;
import com.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
ParseException;
SimpleDateFormat;
import java.util.Date;
/**
* ⾃定义序列化
**/
public class CustomJsonDateDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = jp.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
以上,接受数据时,会⾃定义进⾏Json序列化,接收Date格式的数据