我正在使用Symfony2,JMS Serializer Bundle,FOS Rest Bundle和Hateoas Bundle开发RESTful服务。当我序列化公司获得更大的细节时,我想要有2个实体用户和公司。 但是,当序列化用户相关公司时,仅显示公司ID和名称对象,或仅显示ID为整数。
我有如下的序列化政策。
用户
Acme\UserBundle\Entity\User:
exclusion_policy: ALL
xml_root_name: user
properties:
id:
expose: true
type: integer
company:
expose: true
type: Acme\CompanyBundle\Entity\Company
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
公司
Acme\CompanyBundle\Entity\Company:
exclusion_policy: ALL
xml_root_name: company
properties:
id:
expose: true
type: integer
name:
expose: true
type: string
address:
expose: true
type: string
phone:
expose: true
type: string
web:
expose: true
type: string
created_date:
expose: true
type: DateTime
updated_date:
expose: true
type: DateTime
status:
expose: true
type: integer
relations:
-
rel: self
href:
route: acme_v1_get_company
parameters:
id: expr(object.getId())
absolute: true
预期输出
{
"id": 1,
"name": "Jenny",
"surname": "Doe",
"picture": "http://google.com/kittens.jpg",
"info": [],
"company": {
"id": 1,
"name": "Demo Company"
}
}
或
{
"id": 1,
"name": "Jenny",
"surname": "Doe",
"picture": "http://google.com/kittens.jpg",
"info": [],
"company": 1
}
我得到了什么
{
"id": 1,
"name": "Jenny",
"surname": "Doe",
"picture": "http://google.com/kittens.jpg",
"info": [],
"company": {
"id": 1,
"name": "Demo Company",
"address": "Lorem ipsum dolor sit amet",
"phone": "0902124440444",
"web": "http://www.demo-company.com",
"created_date": "2015-07-22T11:21:03+0300",
"updated_date": "2015-07-24T01:50:39+0300",
"status": 1
}
}
答案 0 :(得分:2)
您可以使用群组
AppBundle\Entity\User\User:
exclusion_policy: ALL
properties:
lastname:
expose: true
groups: [info]
使用注释,您可以定义在哪个组上显示哪个属性。最后,您可以为您使用的每条路线分配一个组。
或者您可以使用如下虚拟属性:
AppBundle\Entity\User\User:
exclusion_policy: ALL
properties:
[…]
virtual_properties:
getCompanyId:
serialized_name: company
type: string
groups: [info]
您在User实体中创建一个getCompanyId()
方法,该方法返回companyId
答案 1 :(得分:0)
Hateoas做这件事的方式就是关系。
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
会屈服......
{
"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"
},
}
}