由于Long类型返回给前端时,如果数值过大,会导致精度丢失,这时候就需要把Long转成String。
这时候如果专门为其写一个属性来存储,比较麻烦。这时候可以使用fastJson里的标签
@JSONField(serializeUsing = ToStringSerializer.class)
只要在model类上的Long字段加上这个标签,则会返回前端时,把Long转成String
要注意的一点是。serializeUsing 这个属性是在fastjson 1.2.16后才有的。要检查下fastJson的版本
fastjson 反序列化有漏洞,需要自定义反序列化实现类
@SuppressWarnings("unused")
public class LongJsonDeserializer extends JsonDeserializer<Long> {
private static final Logger logger = LoggerFactory.getLogger(LongJsonDeserializer.class);
@Override
public Long deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
String value = jsonParser.getText();
try {
return value == null || value.length() == 0 ? null : Long.valueOf(value);
} catch (NumberFormatException e) {
logger.error("LongJsonDeserializer.deserialize failed:{},cause:{}", e.getMessage(), e.getCause());
throw new RuntimeException("LongJsonDeserializer.deserialize failed");
}
}
}
@SuppressWarnings("unused")
public class LongJsonSerializer extends JsonSerializer<Long> {
@Override
public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
String text = (value == null ? null : String.valueOf(value));
if (text != null) {
jsonGenerator.writeString(text);
}
}
}
dto vo 使用
@JsonSerialize(using = LongJsonSerializer.class)
@JsonDeserialize(using = LongJsonDeserializer.class)
private Long id;
标签:fastjson,String,spring,boot,value,Long,LongJsonDeserializer,null,class
From: https://blog.csdn.net/hjy930226173/article/details/143002314