fastJson按照字符串顺序遍历JSON字段

原文:https://segmentfault.com/a/1190000003015809

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 entry : jsonObj.entrySet()) {
        System.out.println(entry.getKey() + ":" + entry.getValue());
    }
    System.out.println("-------------------");
    System.out.println("有序遍历结果:");
    LinkedHashMap jsonMap = JSON.parseObject(jsonStr, new TypeReference>() {});
    for (Map.Entry entry : jsonMap.entrySet()) {
        System.out.println(entry.getKey() + ":" + entry.getValue());
    }
 }

你可能感兴趣的:(Java)