Java解析yaml
3623 ワード
test.yamlファイルの内容:
直接コード:
実行結果:
Maven依存:
ip: '192.168.102.31'
port: '7788'
spring:
application:
name: cruncher
server:
port2: 9000
monitor_nic:
nic: {name: 'ethA', slot: 0, cpu: 0}
直接コード:
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Map;
import org.yaml.snakeyaml.Yaml;
/**
* @author huiqiang
* @time 2017-12-1 11:48:00
*/
public class a {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws Exception {
// try {
Yaml yaml = new Yaml();
File dumpFile = new File("D:\\test.yaml");
// test.yaml , obj,
Object load =yaml.load(new FileInputStream(dumpFile));
/**Springboot resources
InputStream io = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.yml");
Object load =yaml.load(io);*/
System.out.println(yaml.dump(load));
System.out.println("#############################################################################");
// Map
Map map =(Map)yaml.load(new FileInputStream(dumpFile));
System.out.println(map);
System.out.println("#############################################################################");
/**
for (String key : map.keySet()) {
System.out.println("key= "+ key + "; value= " + map.get(key));
}
Map(key, value) , java.util.LinkedHashMap cannot be cast to java.lang.String
*/
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
Object val = entry.getValue();
if(key.equals("ip") | key.equals("port")){
System.out.println("------map------");
String string = (String)val; // val 7788 String, val {port=9000} String
System.out.println("ket:value "+key+":"+string);
}else{
System.out.println("------LinkedHashMap------");
System.out.println("ket:value "+key+":"+val);
if(key.equals("server")){
Map map1 = (Map) val;
for (String key1 : map1.keySet()) {
// LinkedHashMap value Map
System.out.println("key= "+ key1 + "; value= " + map1.get(key1));
}
}
}
}
// } catch (Exception e) {
// e.printStackTrace();
// }
}
}
実行結果:
ip: 192.168.102.31
port: '7788'
spring:
application: {name: cruncher}
server: {port2: 9000}
monitor_nic:
nic: {name: ethA, slot: 0, cpu: 0}
#############################################################################
{ip=192.168.102.31, port=7788, spring={application={name=cruncher}}, server={port=9000}, monitor_nic={nic={name=ethA, slot=0, cpu=0}}}
#############################################################################
------map------
ket:value ip:192.168.102.31
------map------
ket:value port:7788
------LinkedHashMap------
ket:value spring:{application={name=cruncher}}
------LinkedHashMap------
ket:value server:{port=9000}
key= port2; value= 9000
------LinkedHashMap------
ket:value monitor_nic:{nic={name=ethA, slot=0, cpu=0}}
Maven依存:
org.yaml
snakeyaml
1.26