0

I understand that a JSONObject contains key-value pairs that are not ordered. But, at what point does a JSONObject change its order? For instance, if I have a JSONObject such as

{"p1": 1, "p2": 2}

Will it become unordered if I don't modify it?

sle
  • 165
  • 1
  • 1
  • 8
  • perhaps if HashMap is in use it will be unordered when maps back from Java to JSON – Vadim Dec 05 '17 at 16:57
  • Read this answer: [Does ES6 introduce a well-defined order of enumeration for object properties?](https://stackoverflow.com/a/30919039/691711). You're kind of drifting into undefined behavior. If something is not guarenteed to be ordered, I would say the script engine is permitted to change the ordering whenever it wants depending on the implementation. What are you **actually** trying to accomplish? – zero298 Dec 05 '17 at 17:00
  • @zero298 I am trying to read a JSONObject in two independent areas, and I was just wondering if those two reads would match up order-wise (say when printed). I do believe that I can use TreeMap or LinkedHashMap (as suggested below) to preserve order, but I was just curious if that is absolutely required if the JSONObject is unmodified, say if I'm just passing it in to another method or adding it to a List. – sle Dec 05 '17 at 17:54

1 Answers1

0

If you want to preserve the order predicted by insertion use :

      JSONObject object = new JSONObject(new LinkedHashMap());
Mustapha Belmokhtar
  • 1,231
  • 8
  • 21