YAML的Java實現——JYAML基本原理與示例(2)匯入YAML格式檔案

鍾超發表於2011-11-27

請先閱讀YAML的Java實現——JYAML基本原理與示例(1)匯出資料為YAML格式檔案一文。


1. 定義好的YAML檔案testYaml.yaml

--- &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

或無型別資訊的testYaml2.yaml

--- &0 
age: 24
children: &2 
  - 
    age: 3
    name: boy
  - 
    age: 1
    name: girl
name: Michael Corleone
spouse: 
  age: 24
  children: *2
  name: Floveria Edie
  spouse: *0

2. 匯入YAML檔案

try {
	Person corleone = (Person) Yaml.loadType(dumpFile, Person.class);
	Person corleone2 = (Person) Yaml.loadType(dumpFile2, Person.class);
	output(corleone);
	System.out.println();
	output(corleone2);
} catch (FileNotFoundException e) {
	e.printStackTrace();
}
...
private static void output(Person person) {
	System.out.println("Name: " + person.getName());
	System.out.println("Age: " + person.getAge());
	System.out.println("Spouse: " + person.getSpouse().getName());
	System.out.println("Children: " + person.getChildren()[0].getName() + 
		", " + person.getChildren()[1].getName());
}



相關文章