1. 程式人生 > >com.alibaba.fastjson把JSONObject的一些操作

com.alibaba.fastjson把JSONObject的一些操作

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()); }*/
完成!