Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用Thymeleaf和Spring引导转换器将列表转换为JSON字符串_Java_Json_Spring_Spring Boot_Thymeleaf - Fatal编程技术网

Java 使用Thymeleaf和Spring引导转换器将列表转换为JSON字符串

Java 使用Thymeleaf和Spring引导转换器将列表转换为JSON字符串,java,json,spring,spring-boot,thymeleaf,Java,Json,Spring,Spring Boot,Thymeleaf,我正在开发一个通过Thymeleaf模板生成HTML页面的服务。在其中一个模板中,我希望有一个HTML属性作为JSON字符串。我的上下文中的相关对象是ArrayList。不做任何操作,输出将是“[item1,item2]”,但我想要“[“随机”,“填充”]” 我读过关于Converter和Formatter的书,我认为这是一个不错的选择。但我无法让我的转换系统工作 这是我的自定义转换器: 公共类ListConverter实现转换器(ArrayList,String{ 公共字符串转换(ArrayL

我正在开发一个通过Thymeleaf模板生成HTML页面的服务。在其中一个模板中,我希望有一个HTML属性作为JSON字符串。我的上下文中的相关对象是
ArrayList
。不做任何操作,输出将是
“[item1,item2]”
,但我想要
“[“随机”,“填充”]”

我读过关于
Converter
Formatter
的书,我认为这是一个不错的选择。但我无法让我的转换系统工作

这是我的自定义
转换器

公共类ListConverter实现转换器(ArrayList,String{
公共字符串转换(ArrayList源){
返回新的JSONArray(source.toString();
}
}
主类看起来像

@springboot应用程序
公共类应用程序扩展了WebMVCConfigureAdapter{
公共静态void main(字符串[]args){
run(PageServiceApplication.class,args);
}
@豆子
公共ListConverter ListConverter(){
返回新的ListConverter();
}
@凌驾
公共void addFormatters(FormatterRegistry注册表){
addConverter(listConverter());
}
}
最后,Thymeleaf模板如下所示

<some-webcomponent xmlns:th="http://www.thymeleaf.org"
    th:attrappend="tags=${data.tags} ...">
</some-webcomponent>

因此,
tags
是我的
ArrayList
。我也尝试过使用
${{data.tags}}
${{conversions.conversion(data.tags,'String'}
强制转换,但唯一的方法是将
“[item1,item2]”转换为
“item1,item2”

执行
tags=${new org.json.JSONArray(data.tags)}
是可行的,但我希望在其他地方使用它,可能不仅仅是
ArrayList

因此,我的问题是:

  • 这可能吗
  • 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();
      }
    };
  }
}
@springboot应用程序
公共类应用程序扩展了WebMVCConfigureAdapter{
公共静态void main(字符串[]args){
run(PageServiceApplication.class,args);
}
@豆子
公共转换器(){
返回新转换器(){
公共字符串转换(列表源){
返回新的JSONArray(source.toString();
}
};
}
}
Thymeleaf(标签的双括号)


谢谢您的回答:)
<some-webcomponent xmlns:th="http://www.thymeleaf.org"
    th:attrappend="tags=${{data.tags}} ...">
</some-webcomponent>