Php Symfony-如何将json字符串转换为实体
我想将一个json字符串映射到我的实体Poste 以下是我使用var_dump的json输出:Php Symfony-如何将json字符串转换为实体,php,json,symfony,deserialization,jmsserializerbundle,Php,Json,Symfony,Deserialization,Jmsserializerbundle,我想将一个json字符串映射到我的实体Poste 以下是我使用var_dump的json输出: string(695) "{ "id":2, "user": { "id":1, "username":"tom.smith", "email":"tom.smith@gmail.com" // othe
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
为什么我不能反序列化一个简单的实体poste
谢谢您的
$user
属性在Moodress\Bundle\PosteBundle\Entity\Poste
中指的是Moodress\Bundle\UserBundle\Entity\user
。setUser()
只接受用户对象,不接受数组
我想您应该首先使用“user”数组创建一个$user
,然后将其传递给poste对象。在这种情况下,似乎很难用我写的另一种方式来做
您是否使用JMS序列化程序中正确的expose/type方法映射实体?
$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);