【问题标题】:Passing JSON String to Thymeleaf HTML将 JSON 字符串传递给 Thymeleaf HTML
【发布时间】:2020-05-13 07:19:03
【问题描述】:

我正在尝试将此字符串传递给 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);

它会产生同样的错误。

【问题讨论】:

    标签: html spring-boot thymeleaf


    【解决方案1】:

    您不应该将 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}" />
    

    【讨论】:

      猜你喜欢
      • 2018-11-25
      • 1970-01-01
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      相关资源
      最近更新 更多