How can we change the order of JSON Object using Java?

◇◆丶佛笑我妖孽 提交于 2021-02-11 12:49:47

问题


I am pretty new to JSON and trying to construct a new JSON request file using Java. Here is what I need to achieve

{
  "ID": "9724234234",
  "Details": [
    {
      "Name": "Donny",
      "EmpID": "B572345",
      "country": "India",
      }
   ]
}

Here is my Java code

public static void main(String[] args) {
    JSONObject obb = new JSONObject();
    obb.put("ID", "9724234234");

    JSONArray jsonArray = new JSONArray();
    obb.putAll(obb);
    JSONObject obj = new JSONObject();
    obj.put("Name", "Donny");
    obj.put("EmpID", "B572345");
    obj.put("Country", "India");

    jsonArray.add(obj);

    JSONObject obj1 = new JSONObject();
    obj1.put("Details", jsonArray);

    obb.putAll(obj1);
    System.out.println(obb);
}

What I am getting the JSON as

{
  "Details": [
    {
      "Country": "India",
      "EmpID": "B572345",
      "Name": "Donny"
    }
  ],
  "ID": "9724234234"
}

As you can see, my ID is coming in the incorrect position of the JSON, I want it to come in the first part of JSON. Am I missing anything? Any help is appreciated. Cheers.


回答1:


You cannot specify the order of keys in JSON, and it does not matter. Any code that attempted for some reason to rely on the ordering of the keys would fail. This is the case with most standard hashmap/key-value pair implementations, and in some languages (eg Go), the ordering is deliberately randomised to ensure no-one tries to rely on it.




回答2:


You can't rely on the ordering of elements within a JSON object. JSON libraries are free to rearrange the order of the elements as they see fit. its not a bug.

more information abou json in json.org




回答3:


First of all the ordering of the Json elements hardly matter it can only be eye candy not more than that, however give a try with

public static void main(String[] args) {
JSONObject obb = new JSONObject();


JSONArray jsonArray = new JSONArray();

JSONObject obj = new JSONObject();
obj.put("Name", "Donny");
obj.put("EmpID", "B572345");
obj.put("Country", "India");

jsonArray.add(obj);
obb.put("ID", "9724234234");
obb.putAll(obb);
JSONObject obj1 = new JSONObject();
obj1.put("Details", jsonArray);

obb.putAll(obj1);
System.out.println(obb);

}




回答4:


Use @JsonPropertyOrder annotation on class level and provide the order in which you want your JSON to be created. This will only help you if you are using jackson library for your JSON parsing.

eg.

@JsonPropertyOrder({"name", "id"})
public class Test{
    private int id;
    private String name;
    
    getter/setter
}


来源:https://stackoverflow.com/questions/64691804/how-can-we-change-the-order-of-json-object-using-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!