Reputation: 1052
I have encoded JSON (using ESAPI encoder) in the server side.The client then retrieves the fields of the bean and does further processing.
On the server side
JSONBean bean=new JSONBean();
//populate the bean
Gson gson=new Gson();
String jsonString = gson.toJson(bean);
String JSEscapedStr=ESAPI.encoder().encodeForJavaScript(jsonString);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(JSEscapedStr);
Encoded JSON string
\x7B\x22name\x22\x3A\x22Sameer\x22,\x22company\x22\x3A\x22Company\x22,\x22designation\x22\x3A\x22Developer\x22\x7D
On the client side
var JSONObj=JSON.parse(data);
var name=JSONObj["name"];
var company=JSONObj["company"];
var designation=JSONObj["designation"];
//process these variable in javascript
I have also tried using response.setContentType("plain/text"); in the server side which also doesnot work.
Error
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data when content type is "plain/text"
If I hard code the json String then it works
var jsonEncoded="\x7B\x22name\x22\x3A\x22Sameer\x22,\x22company\x22\x3A\x22Company\x22,\x22designation\x22\x3A\x22Developer\x22\x7D";
var JSONObj=JSON.parse(jsonEncoded);
console.log(JSONObj);
var name=JSONObj["name"];
var company=JSONObj["company"];
var designation=JSONObj["designation"];
console.log(name);
console.log(company);
console.log(designation);
Upvotes: 2
Views: 5100
Reputation: 11
ESAPI.encoder().encodeForJavaScript
is designed to encode params or function arguments for JavaScript-Methods/Functions.Upvotes: 1