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字符串


基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01