Search code examples
javajsonjson-simple

Parsing JSON string and preserving key-data order when using json-simple without manually constructing HashMap


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?


Solution

  • 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.