esparhawk1 / json-simple

Automatically exported from code.google.com/p/json-simple
Apache License 2.0
0 stars 0 forks source link

Problem in JSON string creation #51

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
Hi,

   please consider the code in [1] or attached here: it work as expected and it produces the wanted JSON string.
But if you change line 78 from
System.out.println(JSONValue.toJSONString(userMap));
to
System.out.println(new JSONObject(userMap));
the order of items is not preserved even if I used a LinkedHashMap but I cannot 
understand why we have two different behaviours here.
Any idea?

Thanks
Bye
Piero

[1]https://github.com/ottuzzi/JSON-SIMPLE/blob/master/src/org/json/simple/exampl
e/Wikipedia.java

Original issue reported on code.google.com by ottu...@gmail.com on 29 Aug 2011 at 3:49

Attachments:

GoogleCodeExporter commented 8 years ago
The output is:
{"firstName":"John","lastName":"Smith","age":25,"address":{"streetAddress":"21 
2nd Street","city":"New 
York","state":"NY","postalCode":"10021"},"phoneNumber":[{"type":"home","number":
"212 555-1234"},{"type":"fax","number":"646 555-4567"}]}

Is that right? Isn't it the expected one?

Original comment by fangyid...@gmail.com on 29 Nov 2011 at 3:15

GoogleCodeExporter commented 8 years ago
Hi,

   what I was asking is the difference between:
System.out.println(JSONValue.toJSONString(userMap));
and
System.out.println(new JSONObject(userMap));
In the former the order is preserved but in the latter is not.
To test this behaviour switch the former line with the latter one in 
Wikipedia.java at line 78.

Thanks for your attention
Bye
Piero

Original comment by ottu...@gmail.com on 29 Nov 2011 at 2:58

GoogleCodeExporter commented 8 years ago
Yes. The order is determined by the implementation of the map iterator. For 
JSONObject, it inherits java.util.HashMap and the order of its entry iterator 
is not guaranteed even it accepts an ordered one in its constructor, that's why 
the output is not ordered. 

Original comment by fangyid...@gmail.com on 30 Nov 2011 at 2:18