Closed clentfort closed 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.
i think it should be great if make it optional. Ordered keys is good for some cases such as public api.
No. All JSON specifications specifically say the keys are unordered. If a public API is using ordered keys, then they are using JSON incorrectly.
Agree with @johnjaylward. A JSON reference app has to follow the spec.
You can use Gson
String jsonObject = new JsonParser().parse(json).getAsJsonObject().get("field").toString();
LinkedHashMap details = new Gson().fromJson(jsonObject, LinkedHashMap.class);
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 ?
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.
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 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."
In my opinion it would be useful to replace the
HashMap
inJSONObject
with aLinkedHashMap
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.