亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java 中的 yaml 生成

Java 中的 yaml 生成

臨摹微笑 2024-01-25 21:57:51
我是 Java 新手,在生成 yaml 時遇到問題。我想通過 java 生成一個 yaml 文件,如下所示,我為此使用了 Snake yaml。mart:  details:    name: Koushik    purpose: yaml generation for testing    owner:      - name: Bobby        email: [email protected]      - name: Chaminda        email: [email protected]嘗試了類似下面的內容,但沒有按照我期望的方式實現 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 = "[email protected]";     String notification_name_2 = "Chaminda";     String notification_email_2 = "[email protected]";     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);  }}
查看完整描述

1 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

為了獲得正確的樣式,您需要創建并配置一個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", "[email protected]"),

? ? ? ? ? ? Map.of("name", "Chaminda", "email", "[email protected]")

? ? ));


? ? 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: [email protected]

? ? - name: Chaminda

? ? ? email: [email protected]

另外,您可以創建Representers和Resolvers,以便可以使用自定義類而不是嵌套的Map。



查看完整回答
反對 回復 2024-01-25
  • 1 回答
  • 0 關注
  • 193 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號