Java 中的 yaml 生成

我是 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);

  }

}


临摹微笑
浏览 120回答 1
1回答

慕仙森

为了获得正确的样式,您需要创建并配置一个DumperOptions对象并将其传递给类的构造函数Yaml。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和Resolvers,以便可以使用自定义类而不是嵌套的Map。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java