java使用jyaml序列化与反序列化yaml格式文件

转载自一缕阳光直射你的心扉的博客

maven 依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.yamlgroupId>
    <artifactId>testartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>jarpackaging>

    <name>testname>
    <url>http://maven.apache.orgurl>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.jyamlgroupId>
            <artifactId>jyamlartifactId>
            <version>1.3version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.11version>
            <scope>providedscope>
        dependency>
    dependencies>
project>

对应Person实体类

public class Person {
    private String name;
    private int age;
    private String Sex;
    private List<Person> children;

    //省略 getter and setter method.....
}

java bean序列化为yaml

使用Yaml的dump方法

import com.yaml.entity.Person;
import org.ho.yaml.Yaml;
import org.junit.Test;

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

public class App {

    //写入yaml配置文件
    @Test
    public  void write() {
        /* Initialize data. */
        Person father = new Person();
        father.setName("simon.zhang");
        father.setAge(23);
        father.setSex("man");
        List<Person> children=new ArrayList<Person>();
        for (int i = 8; i < 10; i++) {
            Person child = new Person();
            if (i % 2 == 0) {
                child.setSex("man");
                child.setName("mary" + (i - 7));
            } else {
                child.setSex("fatel");
                child.setName("simon" + (i - 7));
            }
            child.setAge(i);
            children.add(child);
        }
        father.setChildren(children);
        /* Export data to a YAML file. */
        File dumpFile = new File(System.getProperty("user.dir") + "/test/src/main/conf/testYaml.yaml");

        try {
            Yaml.dump(father, dumpFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

序列化结果

--- !bean.Person
age: 23
children: 
  - !bean.Person
    age: 8
    name: mary1
    sex: man
  - !bean.Person
    age: 9
    name: simon2
    sex: fatel
name: simon.zhang
sex: man

yaml反序列化为java bean

用来反序列化的yaml文件

age: 23
children: 
  - 
    age: 8
    name: mary1
    sex: man
  - 
    age: 9
    name: simon2
    sex: fatel
name: simon.zhang
sex: man

使用Yaml的loadType方法,需要提供class信息

    //读取yaml配置文件
    @Test
    public  void  read() throws FileNotFoundException {
        File dumpFile=new File(System.getProperty("user.dir") + "/test/src/main/conf/testYaml.yaml");
        Person father = (Person) Yaml.loadType(dumpFile, Person.class);
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(father.getName())
                .append("\t")
                .append(father.getSex())
                .append("\t")
                .append(father.getAge())
                .append("\t")
                .append(father.getChildren().size());
        System.out.println(stringBuilder.toString());

    }
}

Map结构的yaml文件

示例yaml文件

JDBC.driver: com.mysql.jdbc.Driver
JDBC.url: "jdbc:mysql://127.0.0.1:3306/shipping_local?autoReconnect=true&autoReconnectForPools=true&useUnicode=true&characterEncoding=utf8"
JDBC.username: shipping
JDBC.password: shipping
JDBC.autoCommit: false

读取Map结构

//读取yaml配置文件Map结构
    @Test
    public  void  read2() throws FileNotFoundException {
        File dumpFile=new File(System.getProperty("user.dir") + "/test/src/main/conf/testYaml.yaml");
        Map father =Yaml.loadType(dumpFile, HashMap.class);
        for(Object key:father.keySet()){
            System.out.println(key+":\t"+father.get(key).toString());
        }
    }

output:
在这里插入图片描述

总结

jyaml没有对泛型做支持,因此当涉及到较为复杂的反序列化情况时可能会有阻碍,好在yaml可以无缝转换json,到时候使用成熟的json序列化框架就可以解决此类问题,事实上yaml的主要应用场景也不在序列化网络传输这一块,大家了解一下就好。

你可能感兴趣的:(标记语言,java,web)