jackson对yaml序列化与反序列化

一、前言

  在我们进行自动化的时候,通常是yaml文件存储测试数据,并且以它来进行参数化,那么java语言是如何做到yaml文件的序列化与反序列化的呢

二、maven依赖

        <!-- yaml序列化与反序列化相关的库-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.9.9</version>
        </dependency>

三、反序列化

  1、新建一个maven工程

  2、pom文件引入上面的库

  3、在src/java/下定义bean实体类User.java

public class User {
    public String name;
}

  4、在src/resources下新建user.yaml文件,内容如下:

- name: seveniruby
- name: apple
- name: sj

  5、在src/java/下新建Deserialization.java

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import java.io.IOException;
import java.util.List;

public class Deserialization {

    public static void main(String[] args) throws IOException {

        //定义好mapper,准备对yaml进行解析
       ObjectMapper mapper =  new ObjectMapper ( new YAMLFactory (  ) );

       //使用new TypeReference指定反序列化的类型,这里标明的是是一个用户集合
       TypeReference typeReference = new TypeReference<List<User>>(){};

        //readValue方法读取,有两个参数,yaml文件的路径,要反序列化的类型
        List<User> user = mapper.readValue (
                //使用getResourceAsStream加载参数化文件
                Deserialization.class.getResourceAsStream ( "/user.yaml" ),typeReference );

        //使用java8的流式遍历打印出name
        user.forEach ( u -> System.out.println ( u.name));

    }
}

测试结果:

seveniruby
apple
sj

四、序列化

  123步和上面一样

  4、在src/java/下新建Serialization.java

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;

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

public class Serialization {

    public static void main(String[] args) throws IOException {

        //定义好要序列化的user
        List<String> user = new ArrayList<> ();

        user.add ("zhangsan");
        user.add ( "lisi" );
        user.add ( "wang5" );

        //定义好mapper,并且写文件的时候禁止开头默认写---
        ObjectMapper mapper =  new ObjectMapper ( new YAMLFactory ().disable ( YAMLGenerator.Feature.WRITE_DOC_START_MARKER ));

        //使用new TypeReference指定序列化的类型,这里标明的是是一个用户集合
        TypeReference typeReference = new TypeReference<List<User>>(){};


        //writeValue方法,有两个参数,yaml文件的路径,要序列化的类型
        mapper.writeValue (new File ( "src/main/resources/testUser.yaml"),user);

    }
}

测试结果:

知道、想到、做到、得到
原文地址:https://www.cnblogs.com/Durant0420/p/14912073.html