title: Java and XSS: How to html escape a JSON string to protect against XSS?
body: <p>In Java, we've got some code that takes a complex java object and serializes it to json. It then writes that json directly to the markup of a page, in a script tag, assigning it to a variable.</p>
  
  <pre><code>// Get object as JSON using Jackson
  ObjectWriter jsonWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
  String json = jsonWriter.writeValueAsString(complexObject);
  
  // Write JSON out to page, and assign it to a javascript variable.
  Writer out = environment.getOut();
  out.write("var data = " + json);
  </code></pre>
  
  <p>The complex object can have end user content in it, which could open us up to XSS attacks.</p>
  
  <p><strong>How can I get a json version of the complex java object that has each json attribute HTML escaped, to protect against XSS injection?</strong></p>
  
  <p>I've read the <a href="https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet" rel="noreferrer">OWASP XSS Guide</a> and the best I've come up with so far is this, which HTML escapes the entire JSON string, then undoes the quotes, so it can be assigned to a variable in javascript. I'm sure there are better ways to do this, but this seems to work. Any suggestions?</p>
  
  <pre><code>private String objectToHtmlEscapedJson(Object value) {
      try {
          String result = jsonWriter.writeValueAsString(value);
          result = StringEscapeUtils.escapeHtml(result);
          result = result.replace("&amp;quot;", "\"");
          return result;
      } catch (JsonProcessingException e) {
          return "null";
      }
  }
  </code></pre>