发送一个Jackson转换字符串或JSON对象到HTML页面



我正在尝试使用thymleaf将JSON对象发送到javascript中的属性,但是当接收到值时,所有引号都转换为"

在我的POJO中,我有以下方法:

public class MyObject {
public String toJSON() throws IOException {
StringWriter result = new StringWriter();
if (this.getCaseRegistrations().size() > 0) {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(result, this.caseRegistrations);
}
return result.toString();
}

在其他地方,这个类被创建并准备使用并发送给Spring控制器中的ModelAndView:mav.addObject("myObject", myObject);

在我的html页面中,我有以下内容:

<script type="text/javascript">
$(document).ready(function() {
let registrations = [[ ${myObject.toJSON()} ]]
console.log(registrations);
});

不幸的是,当它运行时,javascript在赋值时失败,并抱怨&。查看源代码,我看到了以下内容:let registrations = [{&quot;prop1&quot;:&quot;val1&quot;, ...}];

当我在java端(在调试模式下)查看字符串时,值看起来是正确的[{ "prop1": "val1", ...}]

我尝试过各种各样的东西,比如let registrations = '[[ ${myObject.toJSON()} ]]'(在这里使用反引号),让registrations = decudeURI[[ ${myObject.toJSON()} ]])[# th:utext="${myObject.toJSON()}"/];。最后一次尝试(使用:text)完全失败。

将POJO转换为JSON并将其分配给html页面上的javascript变量的正确方法是什么?(Java-Spring-Thymeleaf)

我在这方面没有太多经验,但是我可以帮你给出一个场景

  1. 在发送到js之前捕获json数据
  2. 然后使用像strrplace()我不知道,如果你知道一些其他的函数[http://w3schools.com/php/func_string_str_replace.asp]看看这里,它将取代所有的括号。第一个参数将是你想要替换的,第二个参数将是你想要替换的。

在我的例子中,它就像,

$user=str_replace("'[',']','{','}'",(my json variable data));

最新更新