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. 快去试试吧~