JsonSerialize与 JsonDeserialize使用
1、已注解方式使用
@JsonDeserialize(using= DateJsonDeserializer.class)
@JsonSerialize(using= DateJsonSerializer.class)
private Date time;
2、自定义实现类
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));
}
}
</article>
网友评论