Symfony - 将 json 反序列化为实体数组 [英] Symfony - Deserialize json to an array of entities

查看:43
本文介绍了Symfony - 将 json 反序列化为实体数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过 get API 调用收到的 json 对象.我进行此调用以接收对象列表.这是一个帖子列表......所以我有一个帖子对象数组.

I have a json object that I received by making a get API call. I make this call to receive a list of objects. It's a list of post... So I have an array of Post Objects.

这里的输出:

{
    "total":2,
    "data":[
      {
        "id":2,
        "user":{
          "id":1,
          "username":"sandro.tchikovani"             
        },
        "description":"cool",
        "nb_comments":0,
        "nb_likes":0,
        "date_creation":"2014-04-13T20:07:34-0700"
      },
      {
        "id":1,
        "user":{
           "id":1,
           "username":"sandro.tchikovani",
         },
        "description":"Premier pooooste #lol",
        "nb_comments":0,
        "nb_likes":0,
        "date_creation":"2014-04-13T15:15:35-0700"
      }
    ]
 }

我想反序列化数据部分...问题是 Symfony 中的 Serializer 给了我一个错误......

I would like to deserialize the data part... The problem is that the Serializer in Symfony gives me an error ...

我遇到的错误:

Class array<MoodressBundlePosteBundleEntityPoste> does not exist

我如何反序列化:

$lastPosts = $serializer->deserialize($data['data'], 'array<MoodressBundlePosteBundleEntityPoste>', 'json');

我如何反序列化数据数组...拥有一组 Postes.我想给我的观点 .twig 一个数组 Poste ......我在反序列化时确实精确了类型......所以我找不到问题所在......

How can I deserialze the data array... To have an array of Postes. I want to give to my view .twig an array Poste... I did precise the type when I deserialize... So I can't find what is the problem...

谢谢.

推荐答案

错误很明显.您的字符串不匹配任何现有的类.

The error is pretty clear. Your string does not match any existant class.

官方文档中的例子说:

$person = $serializer->deserialize($data,'AcmePerson','xml');

在你的情况下,它应该更像是:

In your case it should be more like:

$person = $serializer->deserialize($data['data'],'MoodressBundlePosteBundleEntityPoste','json');

更新:

那好吧.

首先,您的 json 文件似乎无效(使用 http://jsonlint.com/ 测试它).小心点.

First, your json file does not seem to be valid (use http://jsonlint.com/ to test it). Be careful of that.

其次,您必须使用

$data = json_decode($yourJsonFile, true);

然后您可以使用

foreach($data['data'] as $result)
{
    /* Here you can hydrate your object manually like:
    $person = new Person();
    $person->setId($user['id']);
    $person->setDescription($user['description']);

    Or you can use a denormalizer. */
}

这篇关于Symfony - 将 json 反序列化为实体数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆