SnakeYAML Maven:
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.21</version>
</dependency>
User.class:
/**User*/
public class User{
/**name*/
private String name;
/**age*/
private int age;
/**
* @param name Name
*/
public void setName(String name){this.name=name;}
/**
* @return name
*/
public String getName(){return this.name;}
/**
* @param age Age
*/
public void setAge(int age){this.age=age;}
/**
* @return age
*/
public int getAge(){return this.age;}
}
user.yaml:
{age: 20, name: cyfang}
Java Code:
import org.yaml.snakeyaml.Yaml;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class MyTest {
public static void main(String []args) throws IOException {
//Write yaml
String path = MyTest.class.getResource("").getPath()+"user.yaml";
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "cyfang");
map.put("age", 20);
FileWriter writer = new FileWriter(path);
Yaml yaml = new Yaml();
yaml.dump(map, writer);
writer.flush();
writer.close();
//read yaml
User user = yaml.loadAs(MyTest.class.getResourceAsStream("user.yaml"), User.class);
System.out.printf("%s %d\n",user.getName(), user.getAge());
}
}
執行結果:
參考資料:
https://www.baeldung.com/java-snake-yaml