JSON字符串解析成key-value获取键值对的值
程序员文章站
2022-06-12 20:16:24
...
最近在做日志解析这块,记录一下
转为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<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
//通过key获取value
String name = jsonObject.getString("name");
int id = jsonObject.getInt("id");
int age = jsonObject.getInt("age");
int num = jsonObject.getInt("num");
//分割线------------------------
//直接获取key-value
Iterator<String> it = jsonObject.keys();
while(it.hasNext()){
String key = it.next();
Object value = jsonObject.get(key)+"";
System.out.println(key+" : "+value);
}
}
上一篇: 43 Tips for Optimizing PHP code
下一篇: 分别获取json对象的键值