Sto*_*eak 7 php symfony fosrestbundle jmsserializerbundle
use JMS\Serializer\SerializationContext;
$context = SerializationContext::create()->setGroups(array(
'Default', // Serialize John's name
'manager_group', // Serialize John's manager
'friends_group', // Serialize John's friends
'manager' => array( // Override the groups for the manager of John
'Default', // Serialize John manager's name
'friends_group', // Serialize John manager's friends. If you do not override the groups for the friends, it will default to Default.
),
'friends' => array( // Override the groups for the friends of John
'manager_group' // Serialize John friends' managers.
'manager' => array( // Override the groups for the John friends' manager
'Default', // This would be the default if you did not override the groups of the manager property.
),
),
));
$serializer->serialize($john, 'json', $context);
Run Code Online (Sandbox Code Playgroud)
在FOSRestBundle中,我使用@View带有serializerGroups属性的注释:
/**
* @Rest\Get("/api/users/{id}", name="api_get_user")
* @Rest\View(serializerGroups={"Default", "detail", "friends":{"Default"})
*/
public function getAction(Request $request, User $user = null)
{
return $user;
}
Run Code Online (Sandbox Code Playgroud)
如何使用该注释覆盖子属性?
谢谢.
我终于找到答案了!如果有人发现带有注释的更好和更短的方法,我可以授予赏金(因为我无法找回)。
覆盖嵌套属性的组的唯一方法是从视图获取序列化程序上下文,然后从该视图设置组。这里是:
/**
* @Rest\Get("/api/users/profile", name="api_get_profile")
*/
public function profileAction(Request $request)
{
$user = $this->getUser();
// sets different groups for nested properties
$view = $this->view($user);
$view->getContext()->setGroups(array(
'Default',
'user_detail',
'user_profile',
'friends' => array(
'Default',
)
));
return $this->handleView($view);
}
Run Code Online (Sandbox Code Playgroud)
这样,我profileAction将返回一个具有所有user_detail和user_profile组的用户,但是该friends属性中的项目(包含一个User数组)将仅包含该Default组中定义的属性。
结果如下:
{
"id": 532,
"username": "someuser",
"email": "someuser@example.com",
"enabled": true,
"last_login": "2017-11-10T09:45:51+01:00",
"notification_id": "ABC",
"avatar_id": 3,
"friends": [
{
"id": 530,
"username": "anotheruser",
"avatar_id": 5
},
{
"id": 554,
"username": "johndoe",
"avatar_id": 7
}
]
}
Run Code Online (Sandbox Code Playgroud)
问候。