简体   繁体   中英

How to print JSON Object in java

I am unable to print my json data in sequenced way. My code is given below:

import org.json.simple.JSONObject;

public class SendingJSONDATAinPost {

    public static void main(String[] args) {

        JSONObject shipmentObject = new JSONObject();
        shipmentObject.put("created_at", "2015-09-1001: 50");
        shipmentObject.put("callback_url","callback/url");

        System.out.println("JSON OUTPUT->"+shipmentObject.toJSONString());  
    }
}

And my output is:

JSON OUTPUT-> {"callback_url":"callback\\/url","created_at":"2015-09-1001: 50"}

But I need like this:

JSON OUTPUT-> {"created_at":"2015-09-1001: 50","callback_url":"callback\\/url"}

You can't since this object uses HashMap as storage:

 public class JSONObject extends HashMap

So order will not be kept. This is from javadoc from JSONObject :

JSON object. Key value pairs are unordered.

In order to have your way, you will need to store somewhere input keys in ArrayList or something like that, and then take from JSONObject each value from that list.

JSONObject implements java.util.Map and internally uses HashMap implementation so printing the objects sequentially won't be possible as HashMap doesn't maintains the ordering.

However, in case you want to achieve this functionality, try maintaining two JSONArray objects, one containing all the key values and the other array with their corresponding values . JSONArray implements java.util.List and is capable of maintaining the sequential ordering.

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