【问题标题】:Symfony - how to convert json string to entitySymfony - 如何将json字符串转换为实体
【发布时间】:2014-05-28 21:38:10
【问题描述】:

我想将一个 json 字符串映射到我的实体 Poste。

这是我使用 var_dump 的 json 输出:

string(695) "{
              "id":2,
              "user": {
                  "id":1,
                  "username":"tom.smith",
                  "email":"tom.smith@gmail.com"
                  // other properties of User class (FOSUserBundle)
                 },
              "description":"cool",
              "nb_comments":0,"nb_likes":0,
              "date_creation":"2014-04-13T20:07:34-0700", 
              "is_there_fashtag":false,
              "fashtags":[]
            }"

我尝试使用 jmsserializer 反序列化:

$postes[] = $serializer->deserialize($value, 'Moodress\Bundle\PosteBundle\Entity\Poste', 'json');

我有一个错误:

Catchable Fatal Error: Argument 1 passed to 
     Moodress\Bundle\PosteBundle\Entity\Poste::setUser() must be an instance of
     Moodress\Bundle\UserBundle\Entity\User, array given

为什么我不能反序列化一个简单的实体帖子?

谢谢

【问题讨论】:

标签: php json symfony deserialization jmsserializerbundle


【解决方案1】:

您在Moodress\Bundle\PosteBundle\Entity\Poste 中的$user 属性指的是Moodress\Bundle\UserBundle\Entity\UsersetUser() 只接受一个用户对象,而不是一个数组。

我猜你应该首先用'user'数组创建一个$user,然后将它传递给你的poste对象。在这种情况下,除了我写的here 之外,似乎很难以另一种方式做到这一点。

$data = json_decode($yourJsonFile, true);

$user = new User();
$user->setId($data['user']['id']);
$user->setUsername($data['user']['username']);
// …

$poste = new Poste();
$poste->setId($data['id']);
$poste->setDescription($data['description']);
// …
$poste->setUser($user);

【讨论】:

    猜你喜欢
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多