stleary / JSON-java

A reference implementation of a JSON package in Java.
http://stleary.github.io/JSON-java/index.html
Other
4.53k stars 2.56k forks source link

Replace HashMap with LinkedHashMap in JSONObject #66

Closed clentfort closed 12 years ago

clentfort commented 12 years ago

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.

douglascrockford commented 12 years ago

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.

AmirHossein commented 8 years ago

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

johnjaylward commented 8 years ago

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

stleary commented 8 years ago

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

AlexByte commented 6 years ago

You can use Gson

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

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 ?

johnjaylward commented 4 years ago

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.

Tilko commented 3 years ago

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 ?

stleary commented 3 years ago

@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."