![](/img/trans.png)
[英]Row Mapper/Converter to convert list of object array to a json in spring boot
[英]List to JSON string with Thymeleaf and Spring Boot converter
我正在开发一项通过 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() );
}
}
最后 Thymeleaf 模板看起来像
<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 声明。
弹簧靴:
@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();
}
};
}
}
Thymeleaf(标签的双括号)
<some-webcomponent xmlns:th="http://www.thymeleaf.org"
th:attrappend="tags=${{data.tags}} ...">
</some-webcomponent>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.