YAML的Java實現——JYAML基本原理與示例(1)匯出資料為YAML格式檔案
阿新 • • 發佈:2018-12-29
1. Overview
JYAML是YAML的Java實現,YAML的全稱是YAML Ain't Markup Language,是否定遞迴定義,和LINUX的Linux Is Not UniX是一個意思。其結構之簡單,常常成為匯出或匯入配置檔案、資料結構等應用場景的常用API。
2. Download
http://jyaml.sourceforge.net/index.html
3. Basic Types
YAML包括Sequence和Map兩種基本資料格式。對於Sequence,其每一項會以“-”開頭。對於Map的每一項,key與value之間是用“:"來連線的。從屬關係則用空格來表示。這基本上就是YAML的全部語法了。
4. Sample Code
(1)Data
package com.sinosuperman.yaml; public class Person { private String name; private int age; private Person spouse; private Person[] children; public Person(){ } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setSpouse(Person spouse) { this.spouse = spouse; } public void setChildren(Person[] children) { this.children = children; } public String getName() { return this.name; } public int getAge() { return this.age; } public Person getSpouse() { return this.spouse; } public Person[] getChildren() { return this.children; } }
(2)Export Data(Dump Data to a YAML file)
package com.sinosuperman.yaml; import java.io.File; import java.io.FileNotFoundException; import org.ho.yaml.Yaml; public class TestYaml { public static void main(String[] args) { /* Initialize data. */ Person michael = new Person(); Person floveria = new Person(); Person[] children = new Person[2]; children[0] = new Person(); children[1] = new Person(); michael.setName("Michael Corleone"); michael.setAge(24); floveria.setName("Floveria Edie"); floveria.setAge(24); children[0].setName("boy"); children[0].setAge(3); children[1].setName("girl"); children[1].setAge(1); michael.setSpouse(floveria); floveria.setSpouse(michael); michael.setChildren(children); floveria.setChildren(children); /* Export data to a YAML file. */ File dumpFile = new File("conf/testYaml.yaml"); try { Yaml.dump(michael, dumpFile); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
(3)YAML file
--- &0 !com.sinosuperman.yaml.Person
age: 24
children: &2 !com.sinosuperman.yaml.Person[]
- !com.sinosuperman.yaml.Person
age: 3
name: boy
- !com.sinosuperman.yaml.Person
age: 1
name: girl
name: Michael Corleone
spouse: !com.sinosuperman.yaml.Person
age: 24
children: *2
name: Floveria Edie
spouse: *0
5. 快去試試吧~