繁体   English   中英

Symfony Serializer:将 Json 反序列化为实体

[英]Symfony Serializer: Deserializing Json to Entity

我正在尝试使用 Symfony 的 Serializer 将 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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM