You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony 4 API接口JSON响应斜杠未正确转义问题求助

解决Symfony 4 API返回带转义斜杠JSON的问题

嘿,这个问题我之前也踩过坑,核心原因其实很直白:你现在直接返回了序列化后的JSON字符串,Symfony会把它当成普通文本响应处理,导致客户端看到的是被转义过的内容。下面给你几个靠谱的解决方案:

方案1:用JsonResponse包装已序列化的内容

修改你的index方法的返回语句,把序列化后的字符串传给JsonResponse,同时告诉它内容已经是JSON格式,不需要再二次编码:

use Symfony\Component\HttpFoundation\Response;

public function index(CategoryRepository $categoryRepository, SerializerInterfaceAlias $serializer) {
    $jsonContent = $serializer->serialize(
        $categoryRepository->findall(), 
        'json', 
        ['json_encode_options' => JSON_UNESCAPED_SLASHES]
    );
    // 第四个参数设为true,表示内容已是JSON,无需再次编码
    return new JsonResponse($jsonContent, Response::HTTP_OK, [], true);
}

方案2:序列化数组后交给JsonResponse编码

更简洁的方式是让序列化器返回数组,再由JsonResponse自动处理JSON编码,还能避免手动设置编码选项的麻烦:

public function index(CategoryRepository $categoryRepository, SerializerInterfaceAlias $serializer) {
    $categories = $categoryRepository->findall();
    // 用normalize方法得到数组格式的数据
    $categoryArray = $serializer->normalize($categories, null);
    return new JsonResponse($categoryArray);
}

如果你给实体配置了序列化组(比如用groups注解控制字段返回),记得在normalize的参数里加上:

$categoryArray = $serializer->normalize($categories, null, ['groups' => 'category:read']);

方案3:利用FOSRestBundle的自动序列化

既然你已经引入了FOSRestBundle,完全可以直接返回实体对象/集合,它会自动帮你完成序列化并返回标准JSON响应。首先确保你在config/packages/fos_rest.yaml里开启了视图监听:

fos_rest:
    view:
        view_response_listener: true
    serializer:
        serialize_null: true # 可选配置,允许返回null字段

然后简化你的控制器方法:

public function index(CategoryRepository $categoryRepository) {
    // 直接返回实体集合即可
    return $categoryRepository->findall();
}

验证结果

修改完成后,你的接口应该会返回标准的无转义JSON:

[{"id":3,"name":"toto","logo":"tata","description":"lolo","dateCreated":"2019-05-09T10:30:39+00:00"},{"id":4,"name":"tata","logo":"titi","description":"tutu","dateCreated":"2019-05-09T10:30:49+00:00"}]

内容的提问来源于stack exchange,提问作者Kiloumap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:34:14