snakeyaml:
org.yaml snakeyaml1.29
json:
com.alibaba fastjson1.2.78
common:
2、加载yaml文件,并解析为json对象commons-io commons-io2.11.0
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.*;
public class YamlUtil {
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;
}



