JSON字符串解析成key-value获取键值对的值
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
最近在做日志解析这块,记录一下
转为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);
}
}
如果要获取有序的Map,使用这个方法:
Map<String, Object> dummyMap = JSON.parseObject(str,LinkedHashMap.class, Feature.OrderedField);//关键的地方,转化为有序map
此条代码链接来源:
https://blog.csdn.net/Jason_K0/article/details/88093478
GitHub 加速计划 / js / json
18
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:2 个月前 )
960b763e
5 个月前
8c391e04
8 个月前
更多推荐
已为社区贡献2条内容
所有评论(0)