title: Change ContentType or CharacterEncoding in Java Filter ONLY IF ContentType === JSON
body: <p>I'm trying to ensure that all JSON responses from a Jersey based java application have a UTF-8 character encoding parameter appended to their ContentType header.</p>
  
  <p>So if it's a JSON response, I would like the response header for the <code>Content-Type</code> to be</p>
  
  <blockquote>
    <p>Content-Type: application/json;charset=UTF-8</p>
  </blockquote>
  
  <p><code>EDIT: I know I can do this on a case by case basis, but I'd like to do it globally, so it affects all content responses that have a content type of "application/json".
  </code></p>
  
  <p>If I just try and set the character encoding in my filter regardless of the content type, it works fine. But I only want to set the character encoding if the ContentType is "application/json". I find that the response.getContentType() method always returns null unless I call chain.doFilter first. But if I try and change the Character Encoding after this, it seems to always get overwritten. </p>
  
  <pre><code>import java.io.IOException;
  import javax.servlet.*;
  import javax.servlet.http.*;
  import javax.ws.rs.core.MediaType;
  
  public class EnsureJsonResponseIsUtf8Filter implements Filter
  {
      private class SimpleWrapper extends HttpServletResponseWrapper
      {
          public SimpleWrapper(HttpServletResponse response)
          {
              super(response);
          }
  
          @Override
          public String getCharacterEncoding()
          {
              return "UTF-8";
          }
      }
  
      @Override
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
      {
          chain.doFilter(request, response);
  
          if (response.getContentType() != null &amp;&amp; response.getContentType().contains(MediaType.APPLICATION_JSON))
          {
              response.setCharacterEncoding("UTF-8");
              chain.doFilter(request, new SimpleWrapper((HttpServletResponse) response));
          }
      }
  
      @Override
      public void init(FilterConfig filterConfig) throws ServletException
      {
      }
  
      @Override
      public void destroy()
      {
      }
  }
  </code></pre>
  
  <p>I've seen other <a href="https://stackoverflow.com/questions/9359728/jersey-web-service-json-utf-8-encoding">similar questions</a>, but none them seem to have this issue. I've tried registering my filter as the first, and last filter with no luck.</p>