时间:2022-10-18 11:53:26 | 栏目:JAVA代码 | 点击:次
在项目上使用SpringBoot为框架,调用第三方接口时,返回的参数Date类型,需要自定义进行Json序列化,需要进行处理,接受数据
调用第三方接口,返回参数类型为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,则需要自定义进行系列化
创建接收数据对象,生成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) { this.created = 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为自定义序列化对象,如下:
package com.test; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import java.io.IOException; import java.text.ParseException; import java.text.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格式的数据。
@JsonDeserialize(using= DateJsonDeserializer.class) @JsonSerialize(using= DateJsonSerializer.class) private Date time;
public class DateJsonDeserializer extends JsonDeserializer<Date> { public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public Date deserialize(com.fasterxml.jackson.core.JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, com.fasterxml.jackson.core.JsonProcessingException { try { if(jsonParser!=null&&StringUtils.isNotEmpty(jsonParser.getText())){ return format.parse(jsonParser.getText()); }else { return null; } } catch(Exception e) { System.out.println(e.getMessage()); throw new RuntimeException(e); } } }
public class DateJsonSerializer extends JsonSerializer<Date> { public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(format.format(date)); }