2017-09-22 12 views
6

tôi đọc this article về các nhóm tài sản con trọng:JMS Serializer Overriding nhóm trong FOSRestBundle

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); 

Trong FOSRestBundle Tôi đang sử dụng @View chú thích với serializerGroups tài sản:

/** 
* @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; 
} 

Làm thế nào tôi có thể ghi đè thuộc tính con bằng cách sử dụng chú thích đó?

Cảm ơn.

Trả lời

3

Cuối cùng tôi đã tìm thấy câu trả lời! Nếu ai đó tìm thấy một cách tốt hơn và ngắn hơn với chú thích Tôi có thể trao tiền thưởng (vì tôi không thể lấy lại tiền).

Cách duy nhất để ghi đè nhóm của thuộc tính lồng nhau là nhận được ngữ cảnh bộ nối tiếp từ chế độ xem và đặt nhóm từ đó. Ở đây là:

/** 
* @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); 
} 

Bằng cách này tôi profileAction sẽ trả về một người sử dụng với tất cả các user_detailuser_profile nhóm, nhưng các mục trong friends bất động sản, trong đó có chứa một loạt các tài khoản, chỉ cần sẽ chứa các thuộc tính được định nghĩa trong Default nhóm.

Đây là kết quả:

{ 
    "id": 532, 
    "username": "someuser", 
    "email": "[email protected]", 
    "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 
     } 
    ] 
} 

Greetings.

Các vấn đề liên quan