'Fortify Cross-Site Scripting Persistent on Java Rest API response (JSON string & XML string)

I understand that to fix the cross-site scripting, I need to validate the user input and encode the output to avoid browser execute malicious data.

However my application is just a pure Rest API which return JSON string and XML string, fortify reported cross-site scripting persistent (stored) because the code will query data from db and return to the response

#Java Code
@PostMapping(path = "${api.abc.endpoint}")
public ResponseEntity processRequest(@RequestBody String requestStr,
  HttpServletRequest servletRequest) {

    ResponseEntity<String> response = null;
    String responseStr = "";
    responseStr = processRequest(requestString, servletRequest);

    response = ResponseEntity.ok().body(responseStr);

    return response; //response can be JSON or XML
}

#Original JSON Response
{
  "type":"order",
  "responseCode":"001",
  "responseText":"Success",
  "transDesc":"Value from DB"
}

#Original XML Response
<abc:res xmlns:abc="http://sample.com/abc/">
   <type>order</type>
   <responseCode>001</responseCode>
   <responseText>Success</responseText>
   <transDesc>Value from DB</transDesc>
</abc:res>

I try to encode the output string using the OWASP Java Encoder and I got the below encoded string which changed the response format.

#Encoded JSON Response
{\"type\":\"order\",\"responseCode\":\"001\",\"responseText\":\"Success\",\"transDesc\":\"Value from DB\"}


#Encoded XML Response

<data contentType="application/xml;charset=UTF-8" contentLength="241">
<![CDATA[&lt;abc:res xmlns:abc="http://sample.com/abc/"&gt;&lt;type&gt;order&lt;/type&gt;&lt;responseCode&gt;001&lt;/responseCode&gt;&lt;responseText&gt;Success&lt;/responseText&gt;&lt;transDesc&gt;Value from DB&lt;/type&gt;&lt;/abc:res&gt;]]></data>

How can I actually fix the cross-site scripting persistent in fortify for JSON string and XML string?

Thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source