@JsonRawValue 按原样序列化属性 置顶!
序
@JsonRawValue
注解能够按原样序列化属性。属性值不会被转义或者加引号(或者说,会自动去掉转义,多余的引号)。属性值已经是一个 JSON String,或者属性值已经被加了引号时很有用。
例子
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
标题:@JsonRawValue 按原样序列化属性
作者:jerrycookie
地址:https://www.mmzsblog.cn/articles/2023/07/19/1689755836561.html
如未加特殊说明,文章均为原创,转载必须注明出处。均采用CC BY-SA 4.0 协议!
本网站发布的内容(图片、视频和文字)以原创、转载和分享网络内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。若本站转载文章遗漏了原文链接,请及时告知,我们将做删除处理!文章观点不代表本网站立场,如需处理请联系首页客服。• 网站转载须在文章起始位置标注作者及原文连接,否则保留追究法律责任的权利。
• 公众号转载请联系网站首页的微信号申请白名单!
