JSON-java icon indicating copy to clipboard operation
JSON-java copied to clipboard

Replace HashMap with LinkedHashMap in JSONObject

Open clentfort opened this issue 14 years ago • 9 comments

In my opinion it would be useful to replace the HashMap in JSONObject with a LinkedHashMap to maintain the order of the inserted values. This is would be really helpful if one wants to create JSON files that are easy to read and easy to compare with the original files. Also it is more helpful when iterating through the objects since the values come in the order you expect them.

clentfort avatar Sep 10 '12 10:09 clentfort

JSON specifies that keys are not ordered. There is a hazard that LinkedHashMap could cause applications to depend on ordering, and so break compatibility, and that would be an extremely bad thing.

douglascrockford avatar Sep 11 '12 05:09 douglascrockford

i think it should be great if make it optional. Ordered keys is good for some cases such as public api.

AmirHossein avatar Mar 05 '16 09:03 AmirHossein

No. All JSON specifications specifically say the keys are unordered. If a public API is using ordered keys, then they are using JSON incorrectly.

johnjaylward avatar Mar 05 '16 14:03 johnjaylward

Agree with @johnjaylward. A JSON reference app has to follow the spec.

stleary avatar Mar 05 '16 21:03 stleary

You can use Gson

String jsonObject = new JsonParser().parse(json).getAsJsonObject().get("field").toString();
LinkedHashMap details = new Gson().fromJson(jsonObject, LinkedHashMap.class);

AlexByte avatar Apr 28 '18 13:04 AlexByte

If a public API is using ordered keys, then they are using JSON incorrectly.

you put your mind in jail or what ? ... and god said that JSON must be used only for APIs or what ?

Tilko avatar Nov 10 '20 11:11 Tilko

Yes. JSON was made for data exchange. If you are relying on some ordering of keys, Then you are using something that looks like JSON, but is not. If you need ordering in JSON, you use an Array, not an Object.

johnjaylward avatar Nov 10 '20 14:11 johnjaylward

I tried to imagine a case where the choice of a particular order could be a bad idea, guess what, I did not find any because the JSON spec let us free about it. Have I a lack of imagination ?

Tilko avatar Nov 10 '20 23:11 Tilko

@Tilko Thanks for offering your thoughts on this issue. In this case the project is sticking with unordered due to RFC 8259: "An object is an unordered collection of zero or more name/value pairs".

Let's give the last word to Douglas Crockford, who invented JSON, was the author of this project, and left this comment in issue #37: "This has been tried. What happens is people make applications that depend on that ordering, which breaks interoperability."

stleary avatar Nov 11 '20 02:11 stleary