1

I know that this topic has been talked about, and the use of a LinkedHashMap is a 'hacky' way to maneuver this, but if I'm given thousands of JSON strings as input, and eventually want to output them back in their original form, is there anyway to preserve the order without manually constructing LinkedHashMaps.

For example a string like this

{"key":1,"surname":"Reed","given":"Ryan","address":{"state":"CA","postal":"90210"},"gender":"M"}

Right now if I parse the object like so:

JSONObject jsonObject = (JSONObject) parser.parse(str);
System.out.println(jsonObject);

My output will look like this:

{"surname":"Reed","gender":M,"address":{"postalCode":"90210","state":"CA"},"key":1,"given":"Ryan"}

Is there anyway I can get the output to match exactly like the given input?

jon givony
  • 197
  • 2
  • 3
  • 9

2 Answers2

1

In Json property structure, order does not matter. but if you have specific order in your mind you can use Jackson to order them in you desirable way, both in your server and client apps.

https://www.baeldung.com/jackson

http://www.davismol.net/2016/10/24/jackson-json-using-jsonpropertyorder-annotation-to-define-properties-serialization-order/

Mahdi Rajabi
  • 582
  • 1
  • 4
  • 11
0

I think it is impossible by default.

You can refer to this RFC https://www.ietf.org/rfc/rfc4627.txt

An array is an ordered sequence of zero or more values.

If you want to hack it you can override the data structure and use the data structure which preserves the order.

Ehsan Mashhadi
  • 2,568
  • 1
  • 19
  • 30