【问题标题】:List to JSON string with Thymeleaf and Spring Boot converter使用 Thymeleaf 和 Spring Boot 转换器列出 JSON 字符串
【发布时间】:2017-06-23 09:13:08
【问题描述】:

我正在开发一项通过 Thymeleaf 模板生成 HTML 页面的服务。在其中一个模板中,我希望将 HTML 属性作为 JSON 字符串。我上下文中的相关对象是ArrayList<String>。不做任何事情,输出将是"[item1, item2]",但我想要"["random","stuff"]"

我读过关于ConverterFormatter 的文章,我认为这是要走的路。但我无法让我的转换系统工作。

这是我的自定义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&lt;String&gt;。我也尝试过使用${{data.tags}}${#conversions.convert(data.tags, 'String'} 强制转换,但唯一的做法是将"[item1, item2]" 转为"item1,item2"

使用tags=${new org.json.JSONArray(data.tags)} 可行,但我希望在其他地方拥有它,而且可能不仅适用于ArrayList&lt;String&gt;

所以我的问题是:

  • 这可能吗?
  • Converter 是要走的路吗?
  • 我的配置缺少什么?

谢谢。

【问题讨论】:

    标签: java json spring spring-boot thymeleaf


    【解决方案1】:

    无论出于何种原因,它都使用 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>
    

    【讨论】:

    • 谢谢你的回答:)
    猜你喜欢
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 2022-01-24
    • 2022-01-13
    相关资源
    最近更新 更多