JMS Serializer serialize object in object with diffrent view

安稳与你 提交于 2019-12-06 17:26:10

You can use groups

AppBundle\Entity\User\User:
    exclusion_policy: ALL
    properties:
        lastname:
            expose: true
            groups: [info]

And with an annotation, you can define which property is displayed on which group. And finally, you can assign a group to every route you use.

Or you can use virtual properties like so :

AppBundle\Entity\User\User:
    exclusion_policy: ALL
    properties:
         […]
    virtual_properties:
        getCompanyId:
            serialized_name: company
            type: string
            groups: [info]

And you create a getCompanyId() method in your User entity, that returns the companyId

The more Hateoas way to do it would be with the relations.

Acme\UserBundle\Entity\User:
exclusion_policy: ALL
xml_root_name: user
properties:
    id:
        expose: true
        type: integer
    name:
        expose: true
        type: string
    surname:
        expose: true
        type: string
    picture:
        expose: true
        type: string
relations:
    -
        rel: self
        href:
            route: acme_v1_get_user
            parameters:
                id: expr(object.getId())
            absolute: true
    -
        rel: company
        href:
            route: acme_v1_get_company
            parameters:
                id: expr(object.getCompany().getId())
            absolute: true

Would yield...

{
  "id": 1,
  "name": "Jenny",
  "surname": "Doe",
  "picture": "http://google.com/kittens.jpg",
  "info": []
  "_links": {
    "self": {
      "href": "http://server.com/api/user/1"
    },
    "company": {
      "href": "http://server.com/api/company/1"
    },
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!