![](/img/trans.png)
[英]Thymeleaf - How to compare string with request parameter in html in Thymeleaf tag “th:if”?
[英]Passing JSON String to Thymeleaf HTML
我正在尝试将此字符串传递给 HTML 并使用 thymeleaf 访问其属性:
@GetMapping("/")
public ModelAndView getHome(){
ModelAndView mv = new ModelAndView();
mv.addObject("myjson", "{indexid: \"42\", city: \"Flin Flon\"}");
return mv;
}
在 HTML 中:
<p th:text="${myjson}"></p>
这将返回: {indexid: "42", city: "Flin Flon"}
<p th:text="${myjson.city}"></p>
这将返回: Exception evaluating SpringEL expression: "myjson.city"
我也尝试了以下方法:
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"indexid\": \"42\", \"city\": \"Flin Flon\"}";
JsonNode actualObj = mapper.readTree(jsonString);
mv.addObject("myjson", actualObj);
它会产生相同的错误。
您不应该将 json 字符串添加到模型中。 相反,您应该添加具有相同属性的真实 Java 对象。 例如:
public class Location {
String id;
String city;
public Location(String id, String city) {
this.id = id;
this.city = city;
}
// Add your getters and setters
}
然后,如果将该对象添加到模型中:
mv.addObject("location", new Location("42", "Flin Flon"));
您将能够在 html 中访问该对象:
ID: <span th:text="${location.id}" /><br />
City: <span th:text="${location.city}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.