YAML的Java实现——JYAML基本原理与示例(1)导出数据为YAML格式文件

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值