Java 中的 yaml 生成

yaml generation in Java

我是 Java 的新手,我在生成 yaml 时遇到问题。我想通过 java 生成一个 yaml 文件,如下所示,为此我使用了 snake yaml。

mart:
  details:
    name: Koushik
    purpose: yaml generation for testing
    owner:
      - name: Bobby
        email: bd@abc.com
      - name: Chaminda
        email: cv@def.com

尝试了类似下面的方法,但没有按照我期望的方式实现 yaml。

public class yamlGeneration {

   public static String get_details() {
     String name = "Koushik";
     String purpose = "yaml generation for testing";

     String notification_name_1 = "Bobby";
     String notification_email_1 = "bd@abc.com";
     String notification_name_2 = "Chaminda";
     String notification_email_2 = "cv@def.com";

     Map<String, Object> notification = new LinkedHashMap<>();
     List<Map<String, Object>> owner = new ArrayList<Map<String, Object>>();
     notification.put("name",notification_name_1);
     notification.put("email",notification_email_1);
     owner.add(notification);
     notification.put("name",notification_name_2);
     notification.put("email",notification_email_2);
     owner.add(notification);

     Map<String, Object> details = new LinkedHashMap<>();
     details.put("name",name);
     details.put("purpose",purpose);
     details.put("owner",owner);

     Map<String, Object> mart = new LinkedHashMap<>();
     mart.put("details",details);

     Yaml yaml = new Yaml();
     return yaml.dump(mart).toString();
}

public static void main(String args[]){
     String str = get_details();
     System.out.println(str);
  }
}

要获得正确的样式,您需要创建和配置一个 DumperOptions 对象并将其传递给 Yaml class.

的构造函数
public static void main(String[] args) {
    Map<String, Object> root = new LinkedHashMap<>();
    Map<String, Object> mart = new LinkedHashMap<>();

    Map<String, Object> details = new LinkedHashMap<>();
    details.put("name", "Koushik");
    details.put("purpose", "yaml generation for testing");
    details.put("owner", Arrays.asList(
            Map.of("name", "Bobby", "email", "bd@abc.com"),
            Map.of("name", "Chaminda", "email", "cv@def.com")
    ));

    mart.put("details", details);
    root.put("mart", mart);

    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    System.out.println(yaml.dump(root));
}

输出:

mart:
  details:
    name: Koushik
    purpose: yaml generation for testing
    owner:
    - name: Bobby
      email: bd@abc.com
    - name: Chaminda
      email: cv@def.com

另外,您可以创建 Representers and Resolvers,这样您就可以使用自定义 class 而不是嵌套的 Map