@JsonRawValue 按原样序列化属性

@JsonRawValue 注解能够按原样序列化属性。属性值不会被转义或者加引号(或者说,会自动去掉转义,多余的引号)。属性值已经是一个 JSON String,或者属性值已经被加了引号时很有用。

Example

POJO

public class Report {
    private long id;
    private String name;
    @JsonRawValue
    private String content;
    ...
}    

序列化

public class ExampleMain {
    public static void main(String[] args) throws IOException {
        Report r = new Report();
        r.setId(1);
        r.setName("Test report");
        r.setContent("\"data\"");

        System.out.println("-- before serialization --");
        System.out.println(r);

        ObjectMapper om = new ObjectMapper();
        String jsonString = om.writeValueAsString(r);
        System.out.println("-- after serialization --");
        System.out.println(jsonString);
    }
}

直接序列化为 data,而不是 “data”

-- before serialization --
Report{id=1, name='Test report', content='"data"'}
-- after serialization --
{"id":1,"name":"Test report","content":"data"}

属性值为 JSON String

public class ExampleMain2 {
    public static void main(String[] args) throws IOException {
        Report r = new Report();
        r.setId(1);
        r.setName("Test report");
        r.setContent("{\"author\":\"Peter\", \"content\":\"Test content\"}");

        System.out.println("-- before serialization --");
        System.out.println(r);

        ObjectMapper om = new ObjectMapper();
        String jsonString = om.writeValueAsString(r);
        System.out.println("-- after serialization --");
        System.out.println(jsonString);
    }
}

content 没有以字符串的形式序列化,而是以 JSON 对象的形式序列化

-- before serialization --
Report{id=1, name='Test report', content='{"author":"Peter", "content":"Test content"}'}
-- after serialization --
{"id":1,"name":"Test report","content":{"author":"Peter", "content":"Test content"}}

不使用 @JsonRawValue

content 会以字符串的形式序列化

-- before serialization --
Report{id=1, name='Test report', content='{"author":"Peter", "content":"Test content"}'}
-- after serialization --
{"id":1,"name":"Test report","content":"{\"author\":\"Peter\", \"content\":\"Test content\"}"}

原文链接

Jackson JSON - Using @JsonRawValue to serialize property as it is

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值