AML介绍
YAML 是一种比JSON更直观的表现形式数据序列化的语言,特别适合用来表达或编辑数据结构、各种配置文件,既可以以.yaml结尾,也可以.yml结尾。
YAML语法规则:
-
YAML 文件开始行是 ---,这是 YAML 格式的一部分, 表明一个文件的开始。
-
大小写敏感
-
使用缩进表示层级关系
-
缩进时不允许使用Tab键,只允许使用空格。
-
缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
-
#表示注释,从这个字符一直到行尾,都会被解析器忽略。
YAML值类型:
-
字符串(默认不用加引号,包含空格或特殊字符必须加引号,单引号或双引号都可以)
-
布尔值( true或者false)
-
数字(整数或浮点数)
-
null(可用null或者~)
-
对象
单行语法:
address: {province: 湖南省, city: 长沙市}
多行语法(建议):
address: province: 湖南省 city: 长沙市
-
数组
单行语法:
subject: [语文, 英语]
多行语法(建议):
subject: - 语文 - 英语
例子:
name: 张三age: 20height: 179.9isSingle: falseaddress: province: 湖南省 city: 长沙市hobby: - 游戏 - 电影 - 旅游weight: null
YAML序列化与反序列化
Jackson提供了YAMLFactory,可以方便解析YAML,通过ObjectMapper核心类操作YAML文件
com.fasterxml.jackson.dataformat jackson-dataformat-yaml2.10.2
相关使用:
生成ObjectMapper对象
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
序列化:
1.对象转YAML
Student student = new Student("张三",18);String str = mapper.writeValueAsString(student);
2.Map转YAML
HashMapmap = new HashMap();map.put("error", 1);map.put("msg", "系统错误");String str = mapper.writeValueAsString(map);
反序列化:
1.YAML转对象
String yamlStr = "name: "张三"n" + "age: 111n";//转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: 111n";HashMap hashMap = mapper.readValue(yamlStr, HashMap.class);
福利



