JSON字符串解析成key-value获取键值对的值

最近在做日志解析这块,记录一下

转为map,循环得到key,value

{
	"dt": "VENUS_TDS_V0700R0200B20150601",
	"level": 30,
	"id": "152321043",
	"type": "Alert Log",
	"time": 1467958351859,
	"source": {
		"ip": "172.20.0.6",
		"port": 0,
		"mac": "00-06-f6-87-c5-c0"
	},
	"destination": {
		"ip": "0.0.0.0",
		"port": 0,
		"mac": "00-06-f6-87-c5-c0"
	},
	"protocol": "ICMP",
	"subject": "SCAN_ICMP扫描探测",
	"message": "nic=0; ICMP scan rate, (scaned host num, sec):(11, 1)"
}
 Map maps = (Map) JSON.parse(str);
        System.out.println("这个是用JSON类来解析JSON字符串!!!");
        for (Object map : maps.entrySet()) {
            System.out.println(((Map.Entry) map).getKey() + "     " + ((Map.Entry) map).getValue());
        }

2,根节点为”[]”的json

[{
	"id": 1,
	"name": "china",
	"age": 18,
	"num": 123456
}, {
	"id": 2,
	"name": "hongkong",
	"age": 2,
	"num": 9527
}]
 JSONArray jsonArray=new JSONArray(json);
        for(int i=0;i it = jsonObject.keys();
            while(it.hasNext()){
                String key = it.next();
                Object value = jsonObject.get(key)+"";
                System.out.println(key+"   :    "+value);
            }
        }

如果要获取有序的Map,使用这个方法:

Map dummyMap =  JSON.parseObject(str,LinkedHashMap.class, Feature.OrderedField);//关键的地方,转化为有序map

此条代码链接来源:
https://blog.csdn.net/Jason_K0/article/details/88093478

你可能感兴趣的:(个人BUG集)