JSONObject 转map遍历和直接JSONObject遍历
看JSONObject源码知:
String jsonStr = "{\"size\":\"7.5\",\"width\":\"M (B)\"}";
System.out.println("无序遍历结果:");
JSONObject jsonObj = JSON.parseObject(jsonStr);
for (Map.Entry<String, Object> entry : jsonObj.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println("-------------------");
System.out.println("有序遍历结果:");
LinkedHashMap<String, String> jsonMap = JSON.parseObject(jsonStr, new TypeReference<LinkedHashMap<String, String>>() {
});
for (Map.Entry<String, String> entry : jsonMap.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
JSONObject obj = new JSONObject();
{
obj.put("key1", "value1");
obj.put("key2", "value2");
obj.put("key3", "value3");
}
Map<String, String> params = JSONObject.parseObject(obj.toJSONString(), new TypeReference<Map<String, String>>(){});
System.out.println(params);
//输出:{key3=value3, key2=value2, key1=value1}
String dataAes = AES.decryptFromBase64(data, aeskey); JSONObject jsonObj = JSONObject.parseObject(dataAes); /* * 直接遍历 无序遍历 */ for (Map.Entry<String, Object> entry : jsonObj.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); map.put( entry.getKey(), (String)entry.getValue()); } /* * 转为map后再遍历 */ /*Map<String, String> params = JSONObject.parseObject(jsonObj.toJSONString(), new TypeReference<Map<String, String>>(){}); System.out.println(params); for (Map.Entry<String, String> entry : params.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); map.put( entry.getKey(), entry.getValue()); }*/完成!
所有评论(0)