You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Thymeleaf中如何将Spring MVC模型属性转为JSON作为HTML属性值

方案1:使用Thymeleaf内置#json工具类(最推荐)

Thymeleaf 3.0+版本内置了JSON序列化工具类#json,可以直接在任意表达式位置调用,无需额外配置:

<!-- 同时演示在标签内容和HTML属性中输出JSON数组 -->
<div th:each="station : ${stations}"
     th:data-station-codes="${#json.toString(station.codes)}"
     th:text="${#json.toString(station.codes)}">
</div>

渲染后的结果为:

<div data-station-codes="[&quot;CD1&quot;,&quot;CD2&quot;]">["CD1","CD2"]</div>

属性中的双引号会自动做HTML转义,保证标签语法合法,前端读取属性值时会自动还原为标准JSON格式。

方案2:使用文本内联能力

内联语法不局限于JavaScript标签,开启th:inline="text"后,在标签内容和属性值中都可以直接使用[[${}]]语法实现JSON序列化:

<div th:each="station : ${stations}"
     th:inline="text"
     th:data-station-codes="[[${station.codes}]]">
    [[${station.codes}]]
</div>

渲染效果和方案1完全一致,适合习惯用内联语法的场景。

内容的提问来源于stack exchange,提问作者Teocali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 04:27:03