请求要分两种情况,一种是get请求,直接传参数,一种是post传json字符串的,前一种要用springboot的转换器,后一种自定义反序列化方法
需求1:旧代码不规范,重构规范
前端有如下要求
- 将响应-1改成0
- 将请求0改为-1
响应(序列化)
- 创建Json 序列化器
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* 响应到前端时-1要转换为0
*/
public class Negative1To0Serializer extends JsonSerializer<Integer> {
@Override
public void serialize(Integer value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
gen.writeNumber(format(value));
}
/**
* -1要转换为0
*
* @param value
* @return
*/
private Integer format(Integer value) {
return value == -1 ? 0 : value;
}
}
- 在vo上使用
@JsonSerialize(using = Negative1To0Serializer.class)
@ApiModelProperty(value = "状态(1:正常 -1:关闭)", notes = "int(2)")
private Integer state;
请求(反序列化)
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
/**
* 前端提交的0转-1
*/
public class ZeroToNegative1ToSerializer extends JsonDeserializer<Integer> {
@Override
public Integer deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
Integer value = Integer.valueOf(jsonParser.getText());
return value == 0 ? -1 : value;
}
}
@JsonDeserialize(using = ZeroToNegative1ToSerializer.class)
@ApiModelProperty(value = "状态(1:正常 -1:关闭)", notes = "int(2)")
private Integer state;
需求2:要求驼峰命名
响应VO
@JsonProperty("disabledDate")
@ApiModelProperty(value = "失效时间", notes = "")
private Long disableddate;
请求Query
@JsonAlias("disabledDate")
@ApiModelProperty(value = "失效时间", notes = "bigint(13)")
private Long disableddate;