简体   繁体   English

如何在Java中打印JSON对象

[英]How to print JSON Object in java

I am unable to print my json data in sequenced way. 我无法以顺序方式打印json数据。 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"} 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"} JSON OUTPUT-> {"created_at":"2015-09-1001: 50","callback_url":"callback\\/url"}

You can't since this object uses HashMap as storage: 因为该对象使用HashMap作为存储,所以不能:

 public class JSONObject extends HashMap

So order will not be kept. 因此将不保留订单。 This is from javadoc from JSONObject : 这是来自JSONObject javadoc:

JSON object. JSON对象。 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. 为了拥有自己的方式,您将需要在ArrayList或类似的地方存储输入键,然后从JSONObject获取该列表中的每个值。

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. JSONObject实现java.util.Map,并在内部使用HashMap实现,因此无法顺序打印对象,因为HashMap不能保持顺序。

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对象,一个包含所有键值,另一个包含其对应值的数组。 JSONArray implements java.util.List and is capable of maintaining the sequential ordering. JSONArray实现java.util.List并能够维护顺序。

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

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