对于一些不定项的结果,比如可配置的检查项需要保存检查结果的时候,我们如果使用关系型数据库建表来保存对应数据就很麻烦,我们可以把检查结果序列号成json串保存到数据。
例如:
[
{
"checkRecord": "1",
"picUrls": [
"xxxxxx"
],
"pid": 0,
"pointList": [
{
"checkRes": "1",
"itemId": 6
},
{
"checkRes": "0",
"itemId": 7
},
{
"checkRes": "0",
"itemId": 9
}
]
},
{
"checkRecord": "2",
"picUrls": [
"xxxx1",
"xxxx2"
],
"pid": 0,
"pointList": [
{
"checkRes": "0",
"itemId": 10
},
{
"checkRes": "0",
"itemId": 12
},
{
"checkRes": "0",
"itemId": 18
}
]
}
]
但是查询的时候会变成这样
{
"id": 0,
"res":"[{\"checkRecord\":\"string\",\"picUrls\":[\"string\",\"string\"],\"pid\":0,\"pointList\":[{\"checkRes\":\"string\",\"itemId\":0},{\"checkRes\":\"string\",\"itemId\":0},{\"checkRes\":\"string\",\"itemId\":0}]},{\"checkRecord\":\"string\",\"picUrls\":[\"string\",\"string\"],\"pid\":0,\"pointList\":[{\"checkRes\":\"string\",\"itemId\":0},{\"checkRes\":\"string\",\"itemId\":0},{\"checkRes\":\"string\",\"itemId\":0}]}]"
}
原因是java中使用String类型存储数据的时候双引号"会自动添加转义符\导致返回数据序列话的时候无法正常序列化
@JsonRawValue注解可以用于两种方法和字段序列化字段或属性的声明。例如,如果我们在Java类中有一个String字段,则将JSON值括在引号(“”内),但是当我们使用@JsonRawValue批注对该字段进行注释时,Jackson库将忽略引号。
SecurityContextHelper
一个简单的案例
import com.fasterxml.jackson.annotation.JsonRawValue;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
public class JsonRawValueAnnotationTest {
public static void main(String args[]) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Employee());
System.out.println(jsonString);
}
}
//员工阶层
class Employee {
public String emp = "ChatGTP";
@JsonRawValue
public String user= "{\"id\": 18, \"name\": \"Tom\", " + "\"city\": \"shanghai\"}";
}
输出结果
{
"emp" : "ChatGTP",
"user" : {"id": 18, "name": "Tom", "city": "shanghai"}
}