首页 > Web开发 > 详细

fastJson顺序遍历JSON字段

时间:2016-12-13 19:10:32      阅读:198      评论:0      收藏:0      [点我收藏+]

fastJson在把json格式的字符串转换成JSONObject的时候,使用的是HashMap,所以排序规则是根据HASH值排序的,如果想要按照字符串顺序遍历JSON属性,需要在转换的时候指定使用LinkedHashMap代替HashMap。

public static void main(String[] args) {
        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());
        }
    }

fastJson顺序遍历JSON字段

原文:http://www.cnblogs.com/jtlgb/p/6170865.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!