【问题标题】:problem with converting a entity to json using jms_serializer - Symfony 4使用 jms_serializer 将实体转换为 json 的问题 - Symfony 4
【发布时间】:2019-04-25 15:25:52
【问题描述】:

我正在尝试使用 symfony 4 制作一个返回 json 的 api 我创建了一个实体,它工作正常,但它不会将数据库的数据转换为 json 所以来自“Symfony\Component\Serializer\Serializer”的序列化器给我错误

 serialization for the format json is not supported

所以我尝试了 Jms_Serializer 但在官方网站上他们使用的是旧版本的 symfony 我用

安装了这个包
composer require jms/serializer-bundle   

这是控制器中的代码

class ProduitsController extends AbstractController
    {
        /**
         * @Route("/api/produits/cuisine")
         */
        public function index()
        {
            $dc = $this->getDoctrine();

            $Produits=$dc->getRepository(Article::class)->findAll();

            $data= $this->get('jms_serializer')->serialize($Produits,'json');

            return new JsonResponse($data);

        }
    }

我收到了这个错误:ServiceNotFoundException

Service "jms_serializer" not found: even though it exists in the app's 
container, the container inside "App\Controller\ProduitsController" is a
 smaller service locator that only knows about the "doctrine", "form.factory",
 "http_kernel", "parameter_bag", "request_stack", "router", 
"security.authorization_checker", "security.csrf.token_manager", 
"security.token_storage", "serializer", "session" and "twig" services. Try
 using dependency injection instead

一个简单的 json_encode() 结果 给我一个空的json

【问题讨论】:

  • 你真正使用的是哪个 Symfony 版本?你为什么不使用自动装配而不是手动请求服务,就像错误消息告诉你的那样?
  • Symfony 版本 4
  • 有很多以 4 开头的 Symfony 版本。那么我的第二个问题呢?
  • 检查包是否存在于 config/bundles.php
  • 另外,是什么让你认为github.com/schmittjoh/serializer 不支持当前的 Symfony 版本?这就是使用您引用的包时安装的包

标签: json symfony entity symfony4 jms-serializer


【解决方案1】:

没关系,工作正常 问题出在类 AbstractController 我把它改成控制器

class ProduitsController extends Controller
{
    /**
     * @Route("/api/produits/cuisine")
     */
    public function index()
    {
        $dc = $this->getDoctrine();
        $Produits=$dc->getRepository(Article::class)->findAll();
        $data= $this->get('jms_serializer')->serialize($Produits,'json');

        return new JsonResponse($data);

    }
}

【讨论】:

    猜你喜欢
    • 2016-06-18
    • 2014-05-28
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多