Spring Boot使用@JsonComment、JsonSerializer、JsonDeserializer自定义JSON序列化和反序列化

34 篇文章 0 订阅
21 篇文章 0 订阅

参考代码:https://github.com/huiyiwu/spring-boot-simple/spring-boot-mvc

1. 概念

  • 序列化:把Java对象转为字节序列的过程
  • 反序列化:把字节序列恢复为Java对象的过程

2. 对象序列化作用

  • 把对象的字节序列永久地保存在硬盘上,通常存放在一个文件中;(持久化对象)
  • 在网络上传送对象的字节序列。(网络传输对象)

3. 自定义JsonSerializer类

import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.*;


@JsonComponent
public class ClothColorJsonSerializer {
    public static class ClothColorSerializer extends JsonSerializer<ClothColorPojo> {

        @Override
        public void serialize(ClothColorPojo clothColorPojo, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            // 对象转为字节流
            jsonGenerator.writeStartObject();
            jsonGenerator.writeStringField("color",getColor(clothColorPojo.getColor()));
            jsonGenerator.writeEndObject();
        }

        public String getColor(Color color) {
            int r = (int) Math.round(color.getRed()*255.0);
            int g = (int) Math.round(color.getRed()*255.0);
            int b = (int) Math.round(color.getBlue()*255.0);
            return String.format("#%02x%02x%02x",r,g,b);
        }

    }
    public static class ClothColorDeserializer extends JsonDeserializer<ClothColorPojo>{

        @Override
        public ClothColorPojo deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            // 字节流转为对象
            TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
            TextNode colorNode = (TextNode) treeNode.get("color");
            return new ClothColorPojo(Color.web(colorNode.asText()));
        }
    }
}

4. 测试:

  @RequestMapping("serializer")
    public Map<String,Object> jsonSerializer(){
        Map<String,Object> result = new HashMap<>();

        ClothColorPojo clothColorPojo = new ClothColorPojo(Color.ANTIQUEWHITE);
        String colorJson = "{\"color\":\"#f0f8ff\"}";

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            result.put("serializer",objectMapper.writeValueAsString(clothColorPojo));
//            result.put("deserilizer",objectMapper.readValue(colorJson,ClothColorPojo.class));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  result;
    }

测试结果:
序列化测试

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值