简体   繁体   中英

List to JSON string with Thymeleaf and Spring Boot converter

I'm working on a service that produces HTML pages via Thymeleaf templates. In one of those templates I would like to have an HTML attribute as a JSON string. The related Object in my context is an ArrayList<String> . Without doing anything the output would be "[item1, item2]" but I want "["random","stuff"]" .

I've read about Converter and Formatter and I thought that was the way to go. But I cannot get my conversion system to work.

Here is my custom Converter :

public class ListConverter implements Converter(ArrayList<String>, String {
  public String convert (ArrayList<String> source) {
    return new JSONArray(source).toString();
  }
}

The main class looks like

@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() );
  }
}

Finally the Thymeleaf template looks like

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

So tags is my ArrayList<String> . I have also tried forcing the conversion with ${{data.tags}} or with ${#conversions.convert(data.tags, 'String'} but the only this is does is turn "[item1, item2]" to "item1,item2" .

Doing tags=${new org.json.JSONArray(data.tags)} works but I could like to have that elsewhere and probably not only for ArrayList<String> .

So my questions are :

  • is this possible at all ?
  • are Converter the way to go ?
  • what am I missing with the configuration ?

Thank you.

For whatever reason, it works using List instead of ArrayList. Also, I would get rid of the addFormatters method. You just need the bean declaration.

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();
      }
    };
  }
}

Thymeleaf (double bracket for tags)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM