Total Pageviews

2018/03/12

[snakeyaml] How to generate YAML via Java?

Problem
How to generate YAML via Java?
The expected YAML content looks like:
1
2
3
4
5
6
7
8
9
  intents:
  - greet
  - inform
  - others
  - question
  entities:
  - userid
  - is_account_locked
  - pass_company_check


How-To
Add snakeyaml dependency to pom.xml
1
2
3
4
5
 <dependency>
  <groupId>org.yaml</groupId>
  <artifactId>snakeyaml</artifactId>
  <version>1.19</version>
 </dependency>

Here has sample code which implement via snakeyaml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  package test.albert.snakeyaml;
  
  import java.util.Arrays;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  
  import org.yaml.snakeyaml.DumperOptions;
  import org.yaml.snakeyaml.Yaml;
  
  import lombok.AllArgsConstructor;
  import lombok.Data;
  import lombok.extern.slf4j.Slf4j;
  
  @Slf4j
  public class SnakeYamlTest {
  
      public static void main(String[] args) {
          // Set DumperOptions options
          DumperOptions options = new DumperOptions();
          options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
          options.setPrettyFlow(true);
  
          // Create Yaml instance with DumperOptions
          Yaml yaml = new Yaml(options);
  
          // Prepare map data for YAML
          Map<String, Object> map = new HashMap<>();
          map.put("intents", Arrays.asList("greet", "inform", "others", "question"));
          map.put("entities", Arrays.asList("userid", "is_account_locked", "pass_company_check"));
  
          // Serialize a Java object into a YAML String
          String output = yaml.dump(map);
          log.info("\n" + output);
      }
  }



No comments: