1、引入依赖

snakeyaml:

<!-- https://mvnrepository.com/artifact/org.yaml/snakeyaml -->
<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.29</version>
</dependency>

json:

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.78</version>
</dependency>

common:

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

2、加载yaml文件,并解析为json对象


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author liyinlong
 * @since 2021/11/16 10:03 上午
 */
public class YamlUtil {


    /**
     * 将yaml文件加载为标准json对象(加载后的对象类型是JSONObject不是LinkedHashMap)
     * @param filePath 文件路径
     * @return 标注json对象
     */
    private static JSONObject loadAsNormalJsonObject(String filePath) {
        Yaml yaml = new Yaml();
        Map jsonObject = yaml.loadAs(convertToString(filePath), Map.class);
        String jsonStr = JSONUtil.toJsonStr(jsonObject);
        JSONObject normalJsonObj = JSONObject.parseObject(jsonStr);
        return normalJsonObj;
    }

    public static void main(String[] args) throws IOException {
        String source = "/Users/liyinlong/elasticsearch/values.yaml";
        JSONObject srcObject = loadAsNormalJsonObject(source);

        System.out.println(srcObject);
    }

}

3、加载yaml文件,并解析为字符串

    public static String convertToString(String filePath) {
        String conf = null;
        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(filePath));
            conf = IOUtils.toString(in, String.valueOf(StandardCharsets.UTF_8));
            System.out.println(conf);
        } catch (IOException e) {
            log.error("文件读取失败", e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                log.error("文件关闭失败", e);
            }
        }
        return conf;
    }

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐