title: Dynamic Selection Of JsonView in Spring MVC Controller
body: <p>I am aware that it is possible to annotate controller methods with <code>@JsonView(...)</code> to statically define a single view class in Spring MVC. Unfortunately this means that I need a different endpoint for every type of view I might possibly have.</p>
  
  <p>I see other people have asked this <a href="https://stackoverflow.com/questions/23665107/select-jsonview-in-the-spring-mvc-controller">before</a>. While this approach may work, Spring often has many ways of doing the same thing. Sometimes the solution can be much more simple than it first appears if you just have a bit of knowledge about some of the internals.</p>
  
  <p>I'd like to have a single controller endpoint that can dynamically select the appropriate view based on the current principal. Is it possible for me to return a <code>Model</code> with an attribute that contains the appropriate view class or perhaps a <code>MappingJacksonValue</code> instance directly?</p>
  
  <p>I see in <code>org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter#writeInternal</code> there is a snippet of code that determines what view to use:</p>
  
  <pre><code>if (value instanceof MappingJacksonValue) {
              MappingJacksonValue container = (MappingJacksonValue) object;
              value = container.getValue();
              serializationView = container.getSerializationView();
          }
  </code></pre>
  
  <p>Which appears to come from <code>org.springframework.web.servlet.mvc.method.annotation.JsonViewResponseBodyAdvice#beforeBodyWriteInternal</code> but I'm having trouble working out if there is a way I could bypass this just simply by returning a particular value that contains the necessary information for the <code>Jackson2HttpMessageConverter</code> to pick the right view. </p>
  
  <p>Any help much appreciated.</p>