JMS反序列化不与排斥政策工作

问题描述 投票:2回答:1

我工作的一个Symfony的应用程序,我有一个用户实体:

/**
* @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":"[email protected]",
     "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 /串行束2.3

我怎样才能解决这个问题呢?

php symfony deserialization jms-serializer
1个回答
0
投票

另一种方式来做到这一点是使用形式是这样的:

用户类型

<?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
    }
}
?>

这仅仅是一个通过用形式处理和使用形式验证示例的尝试。我希望,这将能够帮助您。

© www.soinside.com 2019 - 2024. All rights reserved.