已经是 json 格式的数据,怎么不 json 格式化返回给前端

问题

数据库里存的数据是 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;
}

该注解作用:

  1. 直接输出原始值:
    当一个方法或字段被 @JsonRawValue 注解时,它的值将不会被转义,而是直接输出到 JSON 中。
    这意味着如果值中包含特殊字符(如双引号 ", 反斜杠 , 等),它们将不会被转义。
  2. 传递预格式化的 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;
}

看效果,没有加多余的斜杠了:
在这里插入图片描述

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值