ObjectMapper 这个类是jackson提供的,主要是用来把对象转换成为一个json字符串。
一、序列化的时候
1.首先自定义一个class类继承JsonSerializer
类的主要功能就是把long转变为string
public class LongToStr 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);
}
}
}
2.然后再需要转换的属性上面添加JsonSerialize注解
@JsonSerialize 是 Jackson 库中的一个注解,用于指定在将 Java 对象序列化为 JSON 格式时,如何进行自定义的序列化处理。
通过这个注解,指定一个自定义的序列化器(serializer),以控制对象的序列化过程。
@JsonSerialize(using = LongToStr.class)
private Long orderId;
二、反序列化的时候
1.首先自定义一个class类继承JsonSerializer
类的主要功能就是把string转变为long
public class StrToLong 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 ? null : Long.parseLong(value);
} catch (NumberFormatException e) {
logger.error("解析长整形错误", e);
return null;
}
}
}
在需要添加的属性上面添加JsonSerialize注解
@JsonSerialize(using = StrToLong.class)
private Long orderId;