Symfony 3 - automatically serialize DateTime objec

2019-06-26 20:49发布

In my project I have some entity with createdAt column.

//...
class Acme
{
    /**
     * @var DateTime
     *
     * @ORM\Column(name="created_at", type="datetime")
     */
    protected $createdAt;
}

I have enabled FOSRestBundle with Symfony serializer:

fos_rest:
    disable_csrf_role: ROLE_API
    param_fetcher_listener: true
    body_listener: true
    format_listener:
        rules:
            - { path: '/', fallback_format: json, prefer_extension: false }
    routing_loader:
        default_format: json
        include_format: false
    view:
        view_response_listener: force

I make select from datebase in AcmeRepository:

public function methodName() 
{
   $qb =  $this->createQueryBuilder('d');
   $s = $qb->select('d.createdAt']);

   return $s->getQuery()->getArrayResult();
}

And in result, in my controller:

$res = $em->getRepository('AppBundle:Acme')->methodName();
return $res;

It's returns json, but instead of [{"created_at": "2016-04-04 12:13:13"}] i'm getting this:

[{"created_at":{"timezone":{"name":"UTC","location":{"country_code":"??","latitude":0,"longitude":0,"comments":""}},"offset":0,"timestamp":1459769277}]

How I can fix this?

1条回答
地球回转人心会变
2楼-- · 2019-06-26 21:27

You can specify the format of the Type defined for the FOS REST module with the proper annotation Type (check here the doc). As example:

use JMS\Serializer\Annotation\Type as JMS;

class Acme
{
    /**
     * @var DateTime
     *
     * @ORM\Column(name="created_at", type="datetime")
     * @JMS\Type("DateTime<'Y-m-d'>")
     */
    protected $createdAt;
}

Hope this help

查看更多
登录 后发表回答