Jackson处理序列化转换的方式
细粒度,范围具体字段 @JsonSerialize
指定当前字段使用 ToStringSerializer 序列化
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
作用范围,根据字段命名或类型
指定范围Long类型转换为String
public class Long2StringJacksonConverter extends JsonSerializer<Long> {
@Override
public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// currentName 为当前字段名
String currentName = jsonGenerator.getOutputContext().getCurrentName();
String text = (value == null ? null : String.valueOf(value));
if (text != null) {
jsonGenerator.writeString(text);
}
}
// 指定转换器所属类型,key为class类型
@Override
public Class<Long> handledType() {
return Long.class;
}
}
jackson2ObjectMapperFacto

本文探讨了如何使用Jackson处理SpringMVC中Long类型数据转换为String,以防止前端数据损失精度。通过@JsonSerialize注解在特定字段应用ToStringSerializer,或者全局配置ObjectMapper注册序列化模块,可以实现这一目标。
最低0.47元/天 解锁文章
2141

被折叠的 条评论
为什么被折叠?



