JAVA 解析 YML

本贴最后更新于 696 天前,其中的信息可能已经斗转星移

YAML介绍

YAML 是一种比JSON更直观的表现形式数据序列化的语言,特别适合用来表达或编辑数据结构、各种配置文件,既可以以.yaml结尾,也可以.yml结尾。

YAML语法规则:

YAML值类型:

例子:

name: 张三
age: 20
height: 179.9
isSingle: false
address:
  province: 湖南省
  city: 长沙市
hobby:
  - 游戏
  - 电影
  - 旅游
weight: null

YAML序列化与反序列化

Jackson提供了YAMLFactory,可以方便解析YAML,通过ObjectMapper核心类操作YAML文件

<dependency>
     <groupId>com.fasterxml.jackson.dataformat</groupId>
     <artifactId>jackson-dataformat-yaml</artifactId>
     <version>2.10.2</version>
</dependency>

相关使用:

生成ObjectMapper对象

ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());

序列化:

1.对象转YAML
Student student = new Student("张三",18);
String str = mapper.writeValueAsString(student);
2.Map转YAML
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("error", 1);
map.put("msg", "系统错误");
String str = mapper.writeValueAsString(map);

反序列化:

1.YAML转对象
String yamlStr = "name: \"张三\"\n" + 
                "age: 111\n";
//转Java对象
Student student = mapper.readValue(yamlStr, Student.class);
//还可以支持将YAML文件转对象
Student student = mapper.readValue(new File("data.yaml"), Student.class);
2.YAML转Map
String yamlStr = "name: \"张三\"\n" +
                "age: 111\n";
HashMap hashMap = mapper.readValue(yamlStr, HashMap.class);
回帖
请输入回帖内容 ...