org.springframework.web.servlet.view.json

## Class MappingJackson2JsonView

- java.lang.Object
- - org.springframework.context.support.ApplicationObjectSupport
  - - org.springframework.web.context.support.WebApplicationObjectSupport
    - - org.springframework.web.servlet.view.AbstractView
      - - org.springframework.web.servlet.view.json.MappingJackson2JsonView

- All Implemented Interfaces:
    Aware, BeanNameAware, ApplicationContextAware, ServletContextAware, View

      public class MappingJackson2JsonView
      extends AbstractView

  Spring MVC `View` that renders JSON content by serializing the model for the current request using Jackson 2's `ObjectMapper`.

  By default, the entire contents of the model map (with the exception of framework-specific classes) will be encoded as JSON. If the model contains only one key, you can have it extracted encoded as JSON alone via `setExtractValueFromSingleKeyModel(boolean)`.

  Since:
    3.1.2
  Author:
    Jeremy Grelle, Arjen Poutsma, Rossen Stoyanchev, Juergen Hoeller
  See Also:
    `MappingJackson2HttpMessageConverter`

- - ### Field Summary

    Fields
    Modifier and Type | Field and Description
    --- | ---
    `static String` | `DEFAULT_CONTENT_TYPE` Default content type: "application/json".

    - ### Fields inherited from class org.springframework.context.support.ApplicationObjectSupport

      `logger`

    - ### Fields inherited from interface org.springframework.web.servlet.View

      `PATH_VARIABLES, RESPONSE_STATUS_ATTRIBUTE, SELECTED_CONTENT_TYPE`

  - ### Constructor Summary

    Constructors
    Constructor and Description
    `MappingJackson2JsonView()` Construct a new `MappingJackson2JsonView`, setting the content type to `application/json`.

  - ### Method Summary

    Methods
    Modifier and Type | Method and Description
    --- | ---
    `protected Object` | `filterModel(Map<String,Object> model)` Filter out undesired attributes from the given model.
    `JsonEncoding` | `getEncoding()` Return the `JsonEncoding` for this view.
    `Set<String>` | `getModelKeys()` Return the attributes in the model that should be rendered by this view.
    `ObjectMapper` | `getObjectMapper()` Return the `ObjectMapper` for this view.
    `Set<String>` | `getRenderedAttributes()` Deprecated. use `getModelKeys()` instead
    `protected void` | `prepareResponse(HttpServletRequest request, HttpServletResponse response)` Prepare the given response for rendering.
    `protected void` | `renderMergedOutputModel(Map<String,Object> model, HttpServletRequest request, HttpServletResponse response)` Subclasses must implement this method to actually render the view.
    `void` | `setDisableCaching(boolean disableCaching)` Disables caching of the generated JSON.
    `void` | `setEncoding(JsonEncoding encoding)` Set the `JsonEncoding` for this view.
    `void` | `setExtractValueFromSingleKeyModel(boolean extractValueFromSingleKeyModel)` Set whether to serialize models containing a single attribute as a map or whether to extract the single value from the model and serialize it directly.
    `void` | `setJsonPrefix(String jsonPrefix)` Specify a custom prefix to use for this view's JSON output.
    `void` | `setModelKey(String modelKey)` Set the attribute in the model that should be rendered by this view.
    `void` | `setModelKeys(Set<String> modelKeys)` Set the attributes in the model that should be rendered by this view.
    `void` | `setObjectMapper(ObjectMapper objectMapper)` Set the `ObjectMapper` for this view.
    `void` | `setPrefixJson(boolean prefixJson)` Indicates whether the JSON output by this view should be prefixed with `"{} && "`.
    `void` | `setPrettyPrint(boolean prettyPrint)` Whether to use the default pretty printer when writing JSON.
    `void` | `setRenderedAttributes(Set<String> renderedAttributes)` Deprecated. use `setModelKeys(Set)` instead
    `void` | `setUpdateContentLength(boolean updateContentLength)` Whether to update the 'Content-Length' header of the response.
    `protected void` | `writeContent(OutputStream stream, Object value, String jsonPrefix)` Write the actual JSON content to the stream.

    - ### Methods inherited from class org.springframework.web.servlet.view.AbstractView

      `addStaticAttribute, createMergedOutputModel, createRequestContext, createTemporaryOutputStream, exposeModelAsRequestAttributes, generatesDownloadContent, getAttributesMap, getBeanName, getContentType, getRequestContextAttribute, getStaticAttributes, isExposePathVariables, render, setAttributes, setAttributesCSV, setAttributesMap, setBeanName, setContentType, setExposePathVariables, setRequestContextAttribute, setResponseContentType, toString, writeToResponse`

    - ### Methods inherited from class org.springframework.web.context.support.WebApplicationObjectSupport

      `getServletContext, getTempDir, getWebApplicationContext, initApplicationContext, initServletContext, isContextRequired, setServletContext`

    - ### Methods inherited from class org.springframework.context.support.ApplicationObjectSupport

      `getApplicationContext, getMessageSourceAccessor, initApplicationContext, requiredContextClass, setApplicationContext`

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait`

- - ### Field Detail

    - #### DEFAULT_CONTENT_TYPE

          public static final String DEFAULT_CONTENT_TYPE

      Default content type: "application/json". Overridable through `AbstractView.setContentType(java.lang.String)`.
      See Also:
        Constant Field Values

  - ### Constructor Detail

    - #### MappingJackson2JsonView

          public MappingJackson2JsonView()

      Construct a new `MappingJackson2JsonView`, setting the content type to `application/json`.

  - ### Method Detail

    - #### setObjectMapper

          public void setObjectMapper(ObjectMapper objectMapper)

      Set the `ObjectMapper` for this view. If not set, a default `ObjectMapper` will be used.

      Setting a custom-configured `ObjectMapper` is one way to take further control of the JSON serialization process. The other option is to use Jackson's provided annotations on the types to be serialized, in which case a custom-configured ObjectMapper is unnecessary.

    - #### getObjectMapper

          public final ObjectMapper getObjectMapper()

      Return the `ObjectMapper` for this view.

    - #### setEncoding

          public void setEncoding(JsonEncoding encoding)

      Set the `JsonEncoding` for this view. By default, UTF-8 is used.

    - #### getEncoding

          public final JsonEncoding getEncoding()

      Return the `JsonEncoding` for this view.

    - #### setJsonPrefix

          public void setJsonPrefix(String jsonPrefix)

      Specify a custom prefix to use for this view's JSON output. Default is none.
      See Also:
        `setPrefixJson(boolean)`

    - #### setPrefixJson

          public void setPrefixJson(boolean prefixJson)

      Indicates whether the JSON output by this view should be prefixed with `"{} && "`. Default is `false`.

      Prefixing the JSON string in this manner is used to help prevent JSON Hijacking. The prefix renders the string syntactically invalid as a script so that it cannot be hijacked. This prefix does not affect the evaluation of JSON, but if JSON validation is performed on the string, the prefix would need to be ignored.

      See Also:
        `setJsonPrefix(java.lang.String)`

    - #### setPrettyPrint

          public void setPrettyPrint(boolean prettyPrint)

      Whether to use the default pretty printer when writing JSON. This is a shortcut for setting up an `ObjectMapper` as follows:

           ObjectMapper mapper = new ObjectMapper();
           mapper.configure(SerializationFeature.INDENT_OUTPUT, true);

      The default value is `false`.

    - #### setModelKey

          public void setModelKey(String modelKey)

      Set the attribute in the model that should be rendered by this view. When set, all other model attributes will be ignored.

    - #### setModelKeys

          public void setModelKeys(Set<String> modelKeys)

      Set the attributes in the model that should be rendered by this view. When set, all other model attributes will be ignored.

    - #### getModelKeys

          public final Set<String> getModelKeys()

      Return the attributes in the model that should be rendered by this view.

    - #### setRenderedAttributes

          @Deprecated
          public void setRenderedAttributes(Set<String> renderedAttributes)

      Deprecated. use `setModelKeys(Set)` instead
      Set the attributes in the model that should be rendered by this view. When set, all other model attributes will be ignored.

    - #### getRenderedAttributes

          @Deprecated
          public final Set<String> getRenderedAttributes()

      Deprecated. use `getModelKeys()` instead
      Return the attributes in the model that should be rendered by this view.

    - #### setExtractValueFromSingleKeyModel

          public void setExtractValueFromSingleKeyModel(boolean extractValueFromSingleKeyModel)

      Set whether to serialize models containing a single attribute as a map or whether to extract the single value from the model and serialize it directly.

      The effect of setting this flag is similar to using `MappingJacksonHttpMessageConverter` with an `@ResponseBody` request-handling method.

      Default is `false`.

    - #### setDisableCaching

          public void setDisableCaching(boolean disableCaching)

      Disables caching of the generated JSON.

      Default is `true`, which will prevent the client from caching the generated JSON.

    - #### setUpdateContentLength

          public void setUpdateContentLength(boolean updateContentLength)

      Whether to update the 'Content-Length' header of the response. When set to `true`, the response is buffered in order to determine the content length and set the 'Content-Length' header of the response.

      The default setting is `false`.

    - #### prepareResponse

          protected void prepareResponse(HttpServletRequest request,
                             HttpServletResponse response)

      Description copied from class: `AbstractView`
      Prepare the given response for rendering.

      The default implementation applies a workaround for an IE bug when sending download content via HTTPS.

      Overrides:
        `prepareResponse` in class `AbstractView`
      Parameters:
        `request` - current HTTP request
        `response` - current HTTP response

    - #### renderMergedOutputModel

          protected void renderMergedOutputModel(Map<String,Object> model,
                                     HttpServletRequest request,
                                     HttpServletResponse response)
                                          throws Exception

      Description copied from class: `AbstractView`
      Subclasses must implement this method to actually render the view.

      The first step will be preparing the request: In the JSP case, this would mean setting model objects as request attributes. The second step will be the actual rendering of the view, for example including the JSP via a RequestDispatcher.

      Specified by:
        `renderMergedOutputModel` in class `AbstractView`
      Parameters:
        `model` - combined output Map (never `null`), with dynamic values taking precedence over static attributes
        `request` - current HTTP request
        `response` - current HTTP response
      Throws:
        `Exception` - if rendering failed

    - #### filterModel

          protected Object filterModel(Map<String,Object> model)

      Filter out undesired attributes from the given model. The return value can be either another `Map` or a single value object.

      The default implementation removes `BindingResult` instances and entries not included in the `renderedAttributes` property.

      Parameters:
        `model` - the model, as passed on to `renderMergedOutputModel(java.util.Map<java.lang.String, java.lang.Object>, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)`
      Returns:
        the value to be rendered

    - #### writeContent

          protected void writeContent(OutputStream stream,
                          Object value,
                          String jsonPrefix)
                               throws IOException

      Write the actual JSON content to the stream.
      Parameters:
        `stream` - the output stream to use
        `value` - the value to be rendered, as returned from `filterModel(java.util.Map<java.lang.String, java.lang.Object>)`
        `jsonPrefix` - the prefix for this view's JSON output (as indicated through `setJsonPrefix(java.lang.String)`/`setPrefixJson(boolean)`)
      Throws:
        `IOException` - if writing failed