Put in a json object adds a value to the first of jsonobject;

Consider the following code snippet:

JSONObject json = new JSONObject(); 

json.put("one", 1); 

json.put("two", 2); 

json.put("three", 3);

If I print jsonobject, it prints like this

{"three":"1","two":"2","one":"1"}

But I want it like that.

{"one":"1","two":"2","three":"3"}

Please, help. Thanks in advance.

+3
source share
1 answer

The documentation at http://www.json.org/javadoc/org/json/JSONObject.html says:

JSONObject is an unordered set of name / value pairs.

In other words, the properties of an object are addressed by name, not by position, and the standard serialized form does not guarantee any particular order.

Strict positioning occurs only with arrays:

JSONArray json = new JSONArray();

json.put("1");
json.put("2");
json.put("3");

json.toString(); // results in ["1", "2", "3"]

sortedKeys() JSONObject , JSON , . Comparator .

+9

Source: https://habr.com/ru/post/1774481/


All Articles