【问题标题】:Symfony Serializer: Deserializing Json to EntitySymfony 序列化器:将 Json 反序列化为实体
【发布时间】:2021-09-27 04:26:53
【问题描述】:

我正在尝试使用 Symfony 的序列化程序将 Json 反序列化为我的实体“DossierDTO”。

class DossierDTO 
{
    #[Groups(['test'])]
    public string $idActeurCreateur; 
   
    #[Groups(['test'])]
    public string $idDossierVise;   
 
    #[Groups(['test'])]
    public string $idProjet;

    public ArrayCollection $personnes;
    public ArrayCollection $terrains;
    .
    .
    .
    more fields

我只想反序列化带有 #[Groups(['test'])] 注释的字段。

这是我获取 json 对象的调用以及我对它的反序列化的尝试:

/**
* Make a request to API
* @param string $method: request method (POST, GET...)
* @param string $suffix: URI suffix (/example)
* @param array $body: request body
* @throws Exception 
* @return ResponseInterface
*/
public function myRequest(string $method, string $suffix, ?array $body): ResponseInterface
    {   
        $jsonContent = is_null($body) ? json_encode(new stdClass) : $this->serializer->serialize($body, 'json');
        try {
            $response = $this->client->request($method, $this->infos["uri"] . $suffix, [
                'headers' => $this->infos["headers"],
                'body' => $jsonContent
                ]);
            } catch (Exception $e) {
                $this->logger->error($e->getMessage());
            }
        $dossier = $this->serializer->deserialize($response->getContent(), DossierDTO::class, 'json', ["groups" => "test"]);
        dd($dossier, $response->getContent());
}

这就是我的转储显示的内容:

所以基本上,我没有得到我想要的字段,即使我删除了“#[Groups(['test'])]”,结果也是一样的。

它总是向我显示两个 ArrayCollection 字段(空)并且只有这些... 我正在使用 Symfony 5.2.9

【问题讨论】:

  • 什么是$this->infos["uri"]$jsonContent?我认为更多的上下文将有助于理解您的问题。 hdDEbutVersion 在您的序列化内容中,是否符合预期?
  • $this->infos["uri"] 正是我从 ParameterBag 设置路径的方式。在我的构造函数中,我注入了 ParameterBagInterface $infos。我从那里获取基本 URL!我在序列化内容中有 60 个字段。我只想反序列化一些字段(那些带有“test”组的字段)。

标签: php json symfony deserialization


【解决方案1】:

从您的屏幕截图中,我可以看到响应 JSON 具有嵌套对象,由“projet”键控。看起来您正在映射不正确的结构。试试这个:

$this->serializer->deserialize($response->getContent()['projet'], DossierDTO::class, 'json', ["groups" => "test"]);

【讨论】:

    猜你喜欢
    • 2014-05-27
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 2012-08-20
    • 2015-01-21
    • 2016-12-21
    • 1970-01-01
    相关资源
    最近更新 更多