![](/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.