一、前言
在我們進行自動化的時候,通常是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); } }
測試結果: