spring中JSON的自定义序列化

方案1:使用@JsonComponent注解自定义JSON的序列化方式。这种方式,会通过JsonSerializer<String>中<>中的类型,取代spring中String类型默认的json序列化方式。

  示例:对象序列化json字符串时,将对象中的指定属性中的值的_变为|

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.springweb.demo.custrule;
 
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.boot.jackson.JsonComponent;
 
import java.io.IOException;
 
 
/**
 * JSON的自定义序列化
 * 可以定义多种方式处理json的序列化
 */
 
@JsonComponent
public class MyJsonFormatter {
 
    /**
     * 特殊字符的转义
     */
 
    public static class SpecialDeCodeProceed extends JsonSerializer<String> {
 
        @Override
        public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            String str = ObjectUtils.isEmpty(value) ? null : value.replace("_", "|");
            gen.writeString(str);
        }
    }
 
}

方案2.使用@JsonSerialize(using = MyJsonFormatter.SpecialDeCodeProceed.class)指定json的序列化方式,这种方式只是修改这一个地方的json序列化方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.springweb.demo.respose;
 
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.springweb.demo.custrule.MyJsonFormatter;
import lombok.Data;
 
@Data
public class TestResp {
 
    @JsonSerialize(using = MyJsonFormatter.SpecialDeCodeProceed.class)
    private String respText;
 
}

测试结果

  接口:

1
2
3
4
5
6
7
8
9
10
11
@PostMapping("/post")
   @ResponseBody
   @Operation(summary = "输出post", description = "post接口", method = "POST")
   @ApiOperationSupport(order = 1)
   @AccessLimit
   public TestResp postString(@RequestBody TestReq request){
       TestResp resp = new TestResp();
       String s = "hello, post method.[" + request.getReqText() + "]";
       resp.setRespText(s);
       return resp;
   }

  

  结果:

 

posted @   话祥  阅读(194)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示