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


GitHub 加速计划 / fastj / fastjson
25.69 K
6.51 K
下载
FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
最近提交(Master分支:3 个月前 )
c942c834 - 1 年前
5bc4709b - 1 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐