springboot @RequestBody使用JsonSerialize与 JsonDeserialize自定义转参数,处理Date日期格式
Posted on 2018-09-25 17:55 季枫 阅读(18718) 评论(0) 编辑 收藏 举报JsonDeserialize:
1、请求接收的是一个json,并且由对象接收
@RequestMapping(value = "/query", method = {RequestMethod.POST},consumes = "application/json") public WebDataListResponse query(@RequestBody(required = true) DataLogQuryEntity dataLogQuryEntity){
2、对象属性的set方法编写注解
DataLogQuryEntity对象中需要接受Date类型的对象:
public class DataLogQuryEntity { @JsonDeserialize(using = DateJsonDeserializer.class) public void setStartTime(Date startTime) { this.startTime = startTime; } }
注lombok的注意一定要写在setter方法上
3、自定义实现
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 org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class DateJsonDeserializer extends JsonDeserializer<Date> { public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public Date deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, 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); } } }
JsonSerialize用法:
1、对象的get方法应用注解
@JsonSerialize(using = CustomDateSerializer.class) public LocalDateTime getUpdateTime() { return updateTime; }
2、自定义实现
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; import java.time.LocalDateTime; public class CustomDateSerializer extends JsonSerializer<LocalDateTime> { @Override public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { gen.writeString(value.toString()); } }