Java解析yaml

来源:互联网 发布:windows一直在准备配置 编辑:程序博客网 时间:2024/06/05 17:04

test.yaml文件内容:

ip: '192.168.102.31'port: '7788'spring:    application:        name: cruncherserver:    port2: 9000monitor_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("test.yaml");//获取test.yaml文件中的配置数据,然后转换为obj,Object load =yaml.load(new FileInputStream(dumpFile));System.out.println(yaml.dump(load));System.out.println("#############################################################################");//也可以将值转换为MapMap<String, String> map =(Map<String, String>)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}则无法强转成StringSystem.out.println("ket:value "+key+":"+string);}else{System.out.println("------LinkedHashMap------");System.out.println("ket:value "+key+":"+val);if(key.equals("server")){Map<String, Integer> map1 = (Map<String, Integer>) 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.31port: '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}}