Symfony Serializer of DateTime Response String

前端 未结 3 664
醉话见心
醉话见心 2020-12-19 17:53

When attempting to perform a doctrine query and serialze it to json (not using JSM, using the symfony serializer) I get the following in the json:

\"\"due\":{\"timez

相关标签:
3条回答
  • 2020-12-19 18:21

    You have 2 ways to get RFC3339 Datetime format ...

    Option 1:

    Add DateTimeNormalizer as normalizer. An example is https://symfony.com/doc/current/components/serializer.html#recursive-denormalization-and-type-safety.

    Change

    $normalizer = array(new ObjectNormalizer());
    

    by

    $normalizer = array(new DateTimeNormalizer(), new ObjectNormalizer());
    

    Option 2

    More simple is using "serializer" container service ... your code will look like ...

    public function blahAction(Request $request)
    {
        $currentUser = $this->getUser();
        $em = $this->getDoctrine()->getManager();
        $blahs = $em->getRepository('AppBundle:blah')->findAllByStatus($currentUser,'TODO');
        $response = new Response($this->get('serializer')->serialize($blahs, 'json'));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }
    

    .. or, if your prefer autowiring way (this code is unchecked)

    public function blahAction(Request $request, \Symfony\Component\Serializer\SerializerInterface $serializer)
    {
        $currentUser = $this->getUser();
        $em = $this->getDoctrine()->getManager();
        $blahs = $em->getRepository('AppBundle:blah')->findAllByStatus($currentUser,'TODO');
        $response = new Response($serializer->serialize($blahs, 'json'));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }
    
    0 讨论(0)
  • 2020-12-19 18:31

    In Symfony 5.1 it's recomended to add a callback function to specify datetime field format.For example:

    use Symfony\Component\Serializer\Serializer;
    use Symfony\Component\Serializer\Encoder\JsonEncoder;
    use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
    use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
    
    
    $dateCallback = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) {
            return $innerObject instanceof \DateTime ? $innerObject->format(\DateTime::ISO8601) : '';
        };
    
        $defaultContext = [
            AbstractNormalizer::CALLBACKS => [
                'created_at' => $dateCallback,
                'updated_at' => $dateCallback
            ],
            AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER =>
                function ($articles, $format, $context)  {
                    return $articles->getId();
                }
        ];
    
        $encoders = [new JsonEncoder()];
        $normalizers = [
            new ObjectNormalizer(null, null, null,
                null, null, null,
                $defaultContext)
        ];
    
        $serializer = new Serializer(
            $normalizers, $encoders
        );
    
        $articles = $serializer->serialize($articles, 'json');
    

    Where $articles = array of App\Entity\Article objects

    You can specify datetime format you need in your callback function.

    0 讨论(0)
  • 2020-12-19 18:36

    Another option is to pass arguments to the default DateTimeNormalizer in services.yaml:

      Symfony\Component\Serializer\Normalizer\DateTimeNormalizer:
        arguments:
          $defaultContext:
            datetime_format: 'Y-m-d\TH:i:s.v\Z'
    
    0 讨论(0)
提交回复
热议问题