Springboot:Java操作Yaml文件

时间:2025-04-04 22:00:49

文章目录

  • pringboot:Java操作Yaml文件
      • 一、介绍
      • 二、语法
        • 对象
        • 数组
        • 纯量
      • 三、使用snakeyaml将yaml文件解析成Javabean
      • 四、使用snakeyaml根据javabean生成yaml文件
      • 五、使用jackson将yaml文件解析成javabean
      • 六、使用jackson根据javabean生成yaml文件

pringboot:Java操作Yaml文件

一、介绍

YAML,也可以叫做YML,是一种人性化的数据序列化语言,类似于XML,JSON

二、语法

  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进时不允许使用Tab键,只允许使用空格。
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • #表示注释,从这个字符一直到行尾,都会被解析器忽略。
对象

写在一行

address: {province: 山东, city: 济南}

写在多行

address:
  province: 山东
  city: 济南
数组

写在一行

hobbyList: [游泳, 跑步]

写在多行

hobbyList:
  - 游泳
  - 跑步
纯量
  • 字符串 默认不用加引号,包含空格或特殊字符必须加引号,单引号或双引号都可以
userId: S123
username: "lisi"
password: '123456'
province: 山东
city: "济南 : ss"
  • 布尔值
success: true
  • 整数
age: 18
  • 浮点数
weight: 66.6
  • NUll
gender: ~
  • 时间 :时间使用ISO8601标准 [ISO8601](/item/ISO 8601/3910715?fr=aladdin)
createDate: 2001-12-14T21:59:43.10+05     

三、使用snakeyaml将yaml文件解析成Javabean

添加依赖

<dependency>
  <groupId></groupId>
  <artifactId>snakeyaml</artifactId>
  <version>1.27</version>
</dependency>

yaml文件,既可以.yaml结尾,也可以以.yml结尾,支持俩种方式的扩展名

userId: 1
username: lisi
password: 123456
address: {province: 山东, city: 济南}
hobbyList: [游泳, 跑步]

代码示例

@Test
    public void yaml2javaBean(){
        String path = System.getProperty("") + "/src/main/resources/prometheus/rules/";
        if (StringUtils.isNotEmpty(path)) {
            Yaml yaml = new Yaml();
            try {
                User user = yaml.loadAs(new FileReader(path), User.class);
                System.out.println(user);
            } catch (FileNotFoundException e) {
                logger.error("yaml文件转换javabean出错:" + e);
            }
        }
    }

    @Data
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    public static class User{
        private Integer userId;
        private String username;
        private String password;
        private Address address;
        private List<String> hobbyList;
    }

    @Data
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    public static class Address{
        private String province;
        private String city;
    }

四、使用snakeyaml根据javabean生成yaml文件

@Test
    public void javaBean2yaml(){
        User user = User.builder().userId(2).username("张三").password("123456")
                .address(new Address("湖北", "武汉"))
                .hobbyList(Arrays.asList("篮球", "足球")).build();
        String fileName = "";
        String path = System.getProperty("") + "/src/main/resources/prometheus/rules/" + fileName;
        Yaml yaml = new Yaml();
        try {
            yaml.dump(user,new FileWriter(path));
            User u = yaml.loadAs(new FileReader(path), User.class);
            System.out.println(u);
        } catch (IOException e) {
            logger.error("javabean转换yaml失败:" + e);
        }
    }

输出结果为

!!$User
address: {city: 武汉, province: 湖北}
hobbyList: [篮球, 足球]
password: '123456'
userId: 2
username: 张三

上面的对象和数组是显示在一行,我们也可以通过自定义序列化显示为多行

@Test
    public void javaBean2yaml2(){
        User user = User.builder().userId(2).username("张三").password("123456")
                .address(new Address("湖北", "武汉"))
                .hobbyList(Arrays.asList("篮球", "足球")).build();
        String fileName = "";
        String path = System.getProperty("") + "/src/main/resources/prometheus/rules/" + fileName;
        //序列化参数
        DumperOptions dumperOptions = new DumperOptions();
        dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        Yaml yaml = new Yaml(dumperOptions);
        try {
            yaml.dump(user,new FileWriter(path));
            User u = yaml.loadAs(new FileReader(path), User.class);
            System.out.println(u);
        } catch (IOException e) {
            logger.error("javabean转换yaml失败:" + e);
        }
    }

输出结果

!!$User
address:
  city: 武汉
  province: 湖北
hobbyList:
- 篮球
- 足球
password: '123456'
userId: 2
username: 张三

关于snakeyaml的更多用法,请查看 snakeyaml文档

五、使用jackson将yaml文件解析成javabean

添加依赖

<dependency>
  <groupId></groupId>
  <artifactId>jackson-dataformat-yaml</artifactId>
  <version>2.12.0</version>
</dependency>

jackson-dataformat-yaml是在snakeyaml的基础上又封装了一层。

@Test
    public void readYaml(){
        String fileName = "";
        String path = System.getProperty("") + "/src/main/resources/prometheus/rules/" + fileName;
        if (StringUtils.isNotBlank(path)){
            YAMLMapper yamlMapper = new YAMLMapper();
            try {
                User user = yamlMapper.readValue(new FileReader(path), User.class);
                System.out.println(user);
            } catch (IOException e) {
                logger.error("读取" + fileName + "文件失败:" + e);
            }
        }
    }

六、使用jackson根据javabean生成yaml文件

@Test
    public void writeYaml() {
        User user = User.builder().userId(2).username("张三").password("123456")
                .address(new Address("湖北", "武汉"))
                .hobbyList(Arrays.asList("篮球", "足球")).build();
        String fileName = "";
        String path = System.getProperty("") + "/src/main/resources/prometheus/rules/" + fileName;
        YAMLMapper yamlMapper = new YAMLMapper();
        try {
            String s = yamlMapper.writeValueAsString(user);
            User u = yamlMapper.readValue(new FileReader(path), User.class);
            System.out.println(s);
            System.out.println(u);
        } catch (IOException e) {
            logger.error("javabean转换yaml失败:" + e);
        }
    }

输出结果

---
userId: 2
username: "张三"
password: "123456"
address:
  province: "湖北"
  city: "武汉"
hobbyList:
- "篮球"
- "足球"

(userId=1, username=lisi, password=123456, address=(province=山东, city=济南), hobbyList=[游泳, 跑步])