JMS反序列化不适用于排除策略

时间:2018-11-17 03:47:03

标签: php symfony deserialization jms-serializer

我正在开发 Symfony 应用程序,并且有一个User实体:

/**
* @ORM\Entity
* @ORM\Table(name="user")
* @Serializer\ExclusionPolicy("all")
*/
class User
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     * @Serializer\Expose()
     */
    private $id;

    /**
     * @var string $email
     *
     * @ORM\Column(name="email", type="string", length=255, unique=true)
     * @Assert\NotBlank()
     * @Assert\Email()
     * @Serializer\Expose()
     */
    private $email;
    /**
     * @ORM\Column(type="string", length=64)
     * @Assert\NotBlank()
     */
    private $password;
}

我试图像这样反序列化对我的实体的请求有效负载:

$data = $this->request->request->all();
$jsonContent = $this->serializer->serialize($data, 'json'); // serializing goes fine
dump($jsonContent);
{
     "email":"John.Doe@domain.com",
     "password":"123"
}
$object = $this->serializer->deserialize($jsonContent, User::class, 'json'); 
dump($object); // I'm getting null values
AppBundle\Entity\User {
  -id: null
  -email: null
  -password: null
}

所以当我尝试使用验证器验证对象时:

$errors = $this->validator->validate($object);

验证失败,显示以下响应:

{
  "errors" : 
  {
     "email": "This value should not be blank.",
     "password": "This value should not be blank."
  }
}

但是,当我删除此行@Serializer\ExclusionPolicy("all")时,一切正常。

我正在使用:

  • Symfony 3.4
  • jms / serializer-bundle 2.3

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

另一种方法是使用如下形式:

UserType

<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email')
            ->add('password')
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\User'
        ));
    }
}
?>

在您的控制器中,您可以:

class UserController extends Controller
{
    /**
     * @Route("/api/users", name="api_users_post_something")
     * @Method("POST")
     */
    public function postSomethingAction(Request $request)
    {
        $data = $this->serializer->deserialize($request->getContent(), 'array', 'json');
        $user = new User();
        $form = $this->createForm(UserType::class, $user, ['csrf_protection' => false]); // disable csrf_protection if you are making api
        $form->submit($data);

        if(!($form->isSubmitted() && $form->isValid())) {
            // Send form errors
        }

        // Persist and flush or do what you want to do
    }
}
?>

这只是通过使用表单进行处理并使用表单验证进行的示例尝试。 我希望那能为您提供帮助。