List to JSON string with Thymeleaf and Spring Boot converter(使用百里叶和Spring Boot转换器将列表转换为JSON字符串)
问题描述
我正在开发一个通过Thymeleaf模板生成HTML页面的服务。在其中一个模板中,我希望将HTML属性作为JSON字符串。我上下文中的相关对象是ArrayList<String>
。如果不执行任何操作,输出将是"[item1, item2]"
,但我需要"["random","stuff"]"
。
我读过Converter
和Formatter
,我认为应该这样做。但我无法使我的转换系统工作。
以下是我的自定义Converter
:
public class ListConverter implements Converter(ArrayList<String>, String {
public String convert (ArrayList<String> source) {
return new JSONArray(source).toString();
}
}
主类看起来像
@SpringBootApplication
public class TheApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(PageServiceApplication.class, args);
}
@Bean
public ListConverter listConverter() {
return new ListConverter();
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter( listConverter() );
}
}
最后,百里叶模板如下所示
<some-webcomponent xmlns:th="http://www.thymeleaf.org"
th:attrappend="tags=${data.tags} ...">
</some-webcomponent>
所以tags
是我的ArrayList<String>
。我还尝试使用${{data.tags}}
或${#conversions.convert(data.tags, 'String'}
强制转换,但这样做的唯一结果是将"[item1, item2]"
转换为"item1,item2"
。
这样做tags=${new org.json.JSONArray(data.tags)}
有效,但我可能希望在其他地方也这样做,而且可能不仅仅是ArrayList<String>
。
所以我的问题是:
- 这是否可能?
Converter
是要走的路吗?- 我在配置中遗漏了什么?
谢谢您。
推荐答案
不管出于什么原因,它使用List而不是ArrayList工作。此外,我还会去掉addFormatters方法。您只需要bean声明。
Spring Boot:
@SpringBootApplication
public class TheApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(PageServiceApplication.class, args);
}
@Bean
public Converter<List<String>, String> converter() {
return new Converter<List<String>, String>() {
public String convert(List<String> source) {
return new JSONArray(source).toString();
}
};
}
}
百里叶(标记的双方括号)
<some-webcomponent xmlns:th="http://www.thymeleaf.org"
th:attrappend="tags=${{data.tags}} ...">
</some-webcomponent>
这篇关于使用百里叶和Spring Boot转换器将列表转换为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用百里叶和Spring Boot转换器将列表转换为JSON字符串


基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01