YAML简介与使用实例

一、YAML介绍

YAML:是YAML Ain't a Markup Language(YAML不是一种置标语言)的递归缩写,早先YAML的意思其实是:Yet Another Markup Language(另外一种置标语言),但为了强调这种语言以数据做为中心,而不是以置标语言为重点,而用返璞词重新命名,YAML的官方定义很简单,即“一种人性化的数据格式定义语言”,其主要功能用途类似于XML或JSON,YAML使用空白字符和分行来分隔数据,且巧妙避开各种封闭符号,如:引号、括号等,以避免这些符号在复杂层次结构中变得难以辨认。YAML的语法与高阶语言类似,可以很简单地表述序列(java中的list)、杂凑表(java中的map)、标量(java中的基本类型等)等数据结构,它重点强调可阅读性。

YAML vs XML对比:

与YAML相似的数据格式定义语言是XML,YAML比XML优越性表现在

> - YAML的可读性好
> - YAML和脚本语言的交互性好
> - YAML使用实现语言的数据类型
> - YAML有一个一致的信息模型
> - YAML易于实现

上面5条是XML不足的地方,同时,YAML也具有XML的下列优点:

> - YAML可以基于流来处理
> - YAML表达能力强,扩展性好

YAML类似于XML的数据描述语言,语法比XML简单很多,YAML试图用一种比XML更敏捷的方式,来完成XML所完成的任务。

二、环境搭建

方式1、maven引入依赖包

	<dependency>
		<groupId>org.yaml</groupId>
		<artifactId>snakeyaml</artifactId>
		<version>1.16</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.dataformat</groupId>
		<artifactId>jackson-dataformat-yaml</artifactId>
		<version>2.7.3</version>
	</dependency>
	<dependency>
		<groupId>org.jyaml</groupId>
		<artifactId>jyaml</artifactId>
		<version>1.3</version>
	</dependency>

方式2:直接引入jar包

在您的工程中引入以下jar即可:

(1)snakeyaml-1.16.jar

(2)Jackson-dataformat-yaml-2.7.3.jar

(3)Jackson-core-2.7.3.jar

(4)jyaml-1.3.jar

三、使用实例

使用的model类:

package la.cewan.model;
/**
 * Person类
 * @author mengfeiyang
 *
 */
public class Person {  
    private String name;  
    private int age;  
    private Person[] children;  
    public Person(){  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public void setAge(int age) {  
        this.age = age;  
    }  
  
    public void setChildren(Person[] children) {  
        this.children = children;  
    }  
    public String getName() {  
        return this.name;  
    }  
    public int getAge() {  
        return this.age;  
    }  

    public Person[] getChildren() {  
        return this.children;  
    }  
}  

1、将Java 对象导出为yaml文件

package la.cewan.yaml;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import la.cewan.model.Person;

import org.ho.yaml.Yaml;

/**
 * yaml文件测试,将对象导出为yaml文件
 * @author mengfeiyang
 *
 */
public class TestYaml {  
      
    public static void main(String[] args) {  
          
    	Person father = new Person();
    	father.setAge(12);
    	father.setName("爷爷");
    	
    	Person child1 = new Person();
    	child1.setAge(10);
    	child1.setName("第一个孩子");
    	
    	Person child2 = new Person();
    	child2.setAge(20);
    	child2.setName("第二个孩子");
    	
    	Person child3 = new Person();
    	child3.setAge(13);
    	child3.setName("第一个孙子");
    	
    	child1.setChildren(new Person[]{child3});
    	father.setChildren(new Person[]{child1,child2});
    	
    	List<Person> pList = new ArrayList<Person>();
    	pList.add(father);
    	pList.add(child1);
    	pList.add(child2);
    	pList.add(child3);
    	
    	HashMap<String,Person> pMap = new HashMap<String,Person>();
    	pMap.put("father", father);
    	pMap.put("child1", child1);
    	pMap.put("child2", child2);
    	pMap.put("child3", child3);
    	
        //String fPath = TestYaml.class.getResource("/testYaml.yaml").getFile();   
        File dumpFile = new File("testYaml.yaml");
        try {  
        	Yaml.config.setSuppressWarnings(false);
            Yaml.dump(father, dumpFile);  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        }  
    }     
}

导出后的yaml文件内容:

--- !la.cewan.model.Person
age: 12
children: !la.cewan.model.Person[]
  - !la.cewan.model.Person
    age: 10
    children: !la.cewan.model.Person[]
      - !la.cewan.model.Person
        age: 13
        name: 第一个孙子
    name: 第一个孩子
  - !la.cewan.model.Person
    age: 20
    name: 第二个孩子
name: 爷爷

2、yaml文件读取

以下实例演示yaml文件中保存的对象映射到实际的java对象类。

package la.cewan.yaml;

import java.io.File;
import java.io.FileNotFoundException;

import org.ho.yaml.Yaml;

import la.cewan.model.Person;

/**
 * 读取yaml文件
 * @author mengfeiyang
 *
 */
public class LoadYamlFile {
	
	public static void main(String[] args) {
		try {  
			File dumpFile = new File("testYaml.yaml");
		    Person corleone = Yaml.loadType(dumpFile, Person.class);  
		    output(corleone);  
		} 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("Children: " + person.getChildren()[0].getName() + ", " + person.getChildren()[1].getName());  
	    System.out.println("GrandChild:"+person.getChildren()[0].getChildren()[0].getName());
	}  
}

执行后的效果:

095542_ultk_2391658.png

3、使用YamlEncoder以流的形式导出yaml文件

package la.cewan.yaml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import la.cewan.model.Person;

import org.ho.yaml.YamlEncoder;

/**
 * 导出yaml文件
 * @author mengfeiyang
 *
 */
public class FileOutStream2Yaml {
	public static void main(String[] args) {
		try {  
			File dumpFile = new File("testYaml.yaml");
		    YamlEncoder yEncoder = new YamlEncoder(new FileOutputStream(dumpFile));  
		    for (int i = 0; i < 3; ++i) { 
		    	Person michael = new Person();
		        michael.setAge(24 + i);  
		        michael.setName("michael"+i);
		        yEncoder.writeObject(michael);  
		        yEncoder.flush();  
		    }  
		} catch (FileNotFoundException e) {  
		    e.printStackTrace();  
		}   
	}
}

导出的testYaml.yaml文件内容为:

--- !la.cewan.model.Person
age: 24
name: michael0
--- !la.cewan.model.Person
age: 25
name: michael1
--- !la.cewan.model.Person
age: 26
name: michael2

4、使用YamlDecoder以流的形式读取Yaml文件

package la.cewan.yaml;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import org.ho.yaml.YamlDecoder;

import la.cewan.model.Person;

/**
 * 读取yaml文件
 * @author mengfeiyang
 *
 */
public class YamlFileInStream {
	public static void main(String[] args) {
		try {  
			File dumpFile = new File("testYaml.yaml");
		    YamlDecoder yDecoder = new YamlDecoder(new FileInputStream(dumpFile));  
		    Person[] persons = {new Person(), new Person(), new Person()};  
		    for (int i = 0; i < 3; ++i) {  
		        persons[i] = (Person) yDecoder.readObject();  
		        System.out.println();  
		        output(persons[i]);  
		    }  
		} catch (FileNotFoundException e) {  
		    e.printStackTrace();  
		} catch (EOFException e) {  
		    e.printStackTrace();  
		}  
	}
	private static void output(Person person) {  
	    System.out.println("Name: " + person.getName());  
	    System.out.println("Age: " + person.getAge());   
	}
}

执行后的效果:

100022_0MFK_2391658.png

四、源码

源码地址:https://yunpan.cn/cBMGItygbcqvh  

访问密码: c220

 

转载于:https://my.oschina.net/u/2391658/blog/710146

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值