springboot详解 yaml_springboot中对yaml文件的解析

importorg.springframework.core.io.Resource;importorg.springframework.lang.NonNull;importorg.springframework.lang.Nullable;importorg.springframework.util.StringUtils;importorg.yaml.snakeyaml.Yaml;importorg.yaml.snakeyaml.reader.UnicodeReader;importjava.io.IOException;import java.util.*;public classYamlUtils {/*** 单个yaml文件处理

*@paramresource

*@return*@throwsIOException*/

public static Map yamlHandler(@NonNull Resource resource) throwsIOException {//返回的结果

Map result = new LinkedHashMap<>();//读取方式

UnicodeReader reader = newUnicodeReader(resource.getInputStream());//单文件处理

Yaml yaml = newYaml();

Object object=yaml.load(reader);//这里只是简单处理,需要多个方式可以自己添加

if (object instanceofMap) {

Map map=(Map) object;

buildFlattenedMap(result, map,null);

}

reader.close();returnresult;

}/*** 单个yaml文件处理

*@paramresources

*@return*@throwsIOException*/

public static Map yamlHandler(@NonNull Resource[] resources) throwsIOException {//返回的结果

Map result = new LinkedHashMap<>();

Yaml yaml= newYaml();//多个文件处理

Iterator iterator =Arrays.stream(resources).iterator();while(iterator.hasNext()) {

Resource resource=iterator.next();

UnicodeReader reader= newUnicodeReader(resource.getInputStream());

Object object=yaml.load(reader);//这里只是简单处理,需要多个方式可以自己添加

if (object instanceofMap) {

Map map=(Map) object;

buildFlattenedMap(result, map,null);

}

reader.close();

}returnresult;

}/*** 这部分代码来至springboot源码部分对yaml的解析

* YamlProcessor.java buildFlattenedMap方法

*@paramresult

*@paramsource

*@parampath*/

private static void buildFlattenedMap(Map result, Mapsource, @Nullable String path) {//循环读取原数据

source.forEach((key, value) ->{//如果存在路径进行拼接

if(StringUtils.hasText(path)) {if (key.startsWith("[")) {

key= path +key;

}else{

key= path + '.' +key;

}

}//数据类型匹配

if (value instanceofString) {

result.put(key, value);

}else if (value instanceofMap) {//如果是map,就继续读取

Map map =(Map)value;

buildFlattenedMap(result, map, key);

}else if (value instanceofCollection) {

Collection collection =(Collection)value;if(collection.isEmpty()) {

result.put(key,"");

}else{int count = 0;

Iterator var7=collection.iterator();while(var7.hasNext()) {

Object object=var7.next();

buildFlattenedMap(result, Collections.singletonMap("[" + count++ + "]", object), key);

}

}

}else{

result.put(key, value!= null ? value : "");

}

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值