Java将yaml文件解析为json对象和字符串对象
1、引入依赖snakeyaml:<!-- https://mvnrepository.com/artifact/org.yaml/snakeyaml --><dependency><groupId>org.yaml</groupId><artifactId>snakeyaml</artifactId><version&g
·
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;
}
更多推荐
已为社区贡献17条内容
所有评论(0)