简体   繁体   English

从第一个元素到最后一个元素迭代json

[英]Iterate json from first to last element

I am getting data from a json whose order of appearance is important. 我正在从JSON接收数据,其出现顺序很重要。 That is, the element at index 0 should literally come before the element at index 1 and so on. 也就是说,索引0处的元素应字面上位于索引1处的元素之前,依此类推。

Using the snippet below to iterate through the json (the keys of each object is to be used also.) 使用下面的代码片段遍历json(也将使用每个对象的键。)

JSONObject jObject = new JSONObject(string);
            Iterator<String> keys = jObject.keys();
            node = doc.createElement("ul");
            while (keys.hasNext()) {
                String _keys = (String) keys.next();
                System.out.println(_keys); //other codes are here}

The problem is this does not visit the json object from first to last. 问题是这不会从头到尾访问json对象。 Have tested with sample json and found out that the order can not really be determined. 用示例json进行了测试,发现顺序不能真正确定。 IS there a way i can achieve this ? 有没有办法可以做到这一点?

A JSON object has no order of members, by definition. 根据定义,JSON对象没有成员顺序。 If the order is important, use an array, if the order is alphabetic, sort the keys and iterate on the sorted list. 如果顺序很重要,请使用数组;如果顺序是字母顺序,请对键进行排序并在已排序的列表上进行迭代。

Use Jackson for Converting JSONObject to LinkedHashMap , which maintains the key order. 使用JacksonJSONObject转换为LinkedHashMap ,以维护密钥顺序。

    LinkedHashMap <String,String> map =
            new ObjectMapper().readValue(<JSON_OBJECT>, LinkedHashMap .class);
    for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

JSON itself provides no order for key data. JSON本身不提供关键数据的顺序。 However, certain JSON libraries allow it. 但是,某些JSON库允许它。 If you're able to use a 3rd party library, json-simple provides a way: https://code.google.com/p/json-simple/ 如果您能够使用第3方库,则json-simple提供了一种方法: https : //code.google.com/p/json-simple/

Instead of creating JSON objects backed by a HashMap, you create a JSON object backed by a LinkedHashMap (From https://code.google.com/p/json-simple/wiki/DecodingExamples#Example_4_-_Container_factory ): 您无需创建由HashMap支持的JSON对象,而是创建由LinkedHashMap支持的JSON对象(来自https://code.google.com/p/json-simple/wiki/DecodingExamples#Example_4_-__Container_factory ):

String jsonText = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
JSONParser parser = new JSONParser();
ContainerFactory containerFactory = new ContainerFactory(){
    public List creatArrayContainer() {
        return new LinkedList();
    }

    public Map createObjectContainer() {
        return new LinkedHashMap();
    }

};

try {
    Map json = (Map)parser.parse(jsonText, containerFactory);
    Iterator iter = json.entrySet().iterator();
    System.out.println("==iterate result==");
    while(iter.hasNext()){
        Map.Entry entry = (Map.Entry)iter.next();
        System.out.println(entry.getKey() + "=>" + entry.getValue());
    }

    System.out.println("==toJSONString()==");
    System.out.println(JSONValue.toJSONString(json));
}
catch(ParseException pe){
    System.out.println(pe);
}

The end result is a Map that will iterate in the proper order. 最终结果是将以正确的顺序进行迭代的Map。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM