How do I create a custom exclusion strategy for JMS Serializer that allows me to make run-time decisions about whether to include a particular field?

后端 未结 2 1725
小蘑菇
小蘑菇 2020-12-31 19:42

As the title says, I am trying to make a run-time decision on whether or not to include fields in the serialization. In my case, this decision will be based on permissions.<

2条回答
  •  庸人自扰
    2020-12-31 20:17

    You just have to create a class that implements JMS\Serializer\Exclusion\ExclusionStrategyInterface

    In your case, you can implement your own custom logic in the shouldSkipProperty method and always return false for shouldSkipClass.

    Example of implementation can be found in the JMS/Serializer repository

    We will reference the created service as acme.my_exclusion_strategy_service below.


    In your controller action:

    addExclusionStrategy($this->get('acme.my_exclusion_strategy_service'));
    
    $serial = $this->get('jms_serializer')->serialize($object, 'json', $context);
    
    return new Response($serial, Response::HTTP_OK, array('Content-Type' => 'application/json'));
    

    Or if you are using FOSRestBundle

    addExclusionStrategy($this->get('acme.my_exclusion_strategy_service'))
    
    $view = new View($object);
    $view->setSerializationContext($context);
    
    // or you can create your own view factory that handles the creation
    // of the context for you
    
    return $this->get('fos_rest.view_handler')->handle($view);
    

提交回复
热议问题