2

我在服务器端对 JSON 进行了编码(使用 ESAPI 编码器)。客户端然后检索 bean 的字段并进行进一步处理。

在服务器端

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);

编码的 JSON 字符串

\x7B\x22name\x22\x3A\x22Sameer\x22,\x22company\x22\x3A\x22Company\x22,\x22designation\x22\x3A\x22Developer\x22\x7D

在客户端

   var JSONObj=JSON.parse(data);
    var name=JSONObj["name"];
    var company=JSONObj["company"];
    var designation=JSONObj["designation"];
    //process these variable in javascript

我也尝试过使用 response.setContentType("plain/text"); 在服务器端也不起作用。

错误

SyntaxError:JSON.parse:当内容类型为“纯文本”时,JSON 数据的第 1 行第 1 列出现意外字符

如果我对json字符串进行硬编码,那么它可以工作

            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);
4

1 回答 1

1
  1. 您应该只编码有效载荷(应该已经在 Gson 本身完成)而不是整个 JSon 树。
  2. ESAPI.encoder().encodeForJavaScript旨在为 JavaScript 方法/函数编码参数或函数参数。
于 2016-11-02T09:44:08.017 回答