问题
数据库里存的数据是 json 格式
返回给前端的在 json 格式上加了很多转义字符:斜杠 \,导致前端解析不了:
代码如下:
@Data
public class ExplainDto implements Serializable {
// questionId 试题ID
private String questionId;
// answers 答案
private String answers;
// analysis 解析
private String analysis;
// comment 点评
private String comment;
// sort 排序
private Integer sort;
}
那要如何处理呢?
能不能不让它再转化了,直接原样输出给前端?
@JsonRawValue 注解
可以在本来就是 json 的字段上加 @JsonRawValue 注解,让它不再加转义字符,看下源码里的注释:
/**
* Marker annotation that indicates that the annotated method
* or field should be serialized by including literal String value
* of the property as is, without quoting of characters.
* This can be useful for injecting values already serialized in JSON or
* passing javascript function definitions from server to a javascript client.
*<p>
* Warning: the resulting JSON stream may be invalid depending on your input value.
*/
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonRawValue
{
/**
* Optional argument that defines whether this annotation is active
* or not. The only use for value 'false' if for overriding purposes
* (which is not needed often); most likely it is needed for use
* with "mix-in annotations" (aka "annotation overrides").
* For most cases, however, default value of "true" is just fine
* and should be omitted.
*/
boolean value() default true;
}
该注解作用:
- 直接输出原始值:
当一个方法或字段被 @JsonRawValue 注解时,它的值将不会被转义,而是直接输出到 JSON 中。
这意味着如果值中包含特殊字符(如双引号 ", 反斜杠 , 等),它们将不会被转义。 - 传递预格式化的 JSON 或 JavaScript 代码:
在某些场景下,可能需要将服务器端的 JSON 字符串或 JavaScript 代码直接注入到客户端的 JavaScript 代码中。
使用 @JsonRawValue 可以确保这些值能够原样传递,而不会被序列化框架错误地转义或修改
优化后的代码:
@Data
public class ExplainDto implements Serializable {
// questionId 试题ID
private String questionId;
// answers 答案
@JsonRawValue
private String answers;
// analysis 解析
@JsonRawValue
private String analysis;
// comment 点评
private String comment;
// sort 排序
private Integer sort;
}
看效果,没有加多余的斜杠了: