简体   繁体   中英

Iterate json from first to last element

I am getting data from a json whose order of appearance is important. That is, the element at index 0 should literally come before the element at index 1 and so on.

Using the snippet below to iterate through the json (the keys of each object is to be used also.)

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. Have tested with sample json and found out that the order can not really be determined. IS there a way i can achieve this ?

A JSON object has no order of members, by definition. 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.

    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. However, certain JSON libraries allow it. If you're able to use a 3rd party library, json-simple provides a way: 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 ):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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