Real answer can be found in specification, json is unordered.However as a human reader I ordered my elements in order of importance. Not only is it a more logic way, it happened to be easier to read. Maybe the author of the specification never had to read JSON, I do.. So, Here comes a fix:
/** * I got really tired of JSON rearranging added properties. * Specification states: * "An object is an unordered set of name/value pairs" * StackOverflow states: * As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit. * I state: * My implementation will freely arrange added properties, IN SEQUENCE ORDER! * Why did I do it? Cause of readability of created JSON document! */private static class OrderedJSONObjectFactory { private static Logger log = Logger.getLogger(OrderedJSONObjectFactory.class.getName()); private static boolean setupDone = false; private static Field JSONObjectMapField = null; private static void setupFieldAccessor() { if( !setupDone ) { setupDone = true; try { JSONObjectMapField = JSONObject.class.getDeclaredField("map"); JSONObjectMapField.setAccessible(true); } catch (NoSuchFieldException ignored) { log.warning("JSONObject implementation has changed, returning unmodified instance"); } } } private static JSONObject create() { setupFieldAccessor(); JSONObject result = new JSONObject(); try { if (JSONObjectMapField != null) { JSONObjectMapField.set(result, new LinkedHashMap<>()); } }catch (IllegalAccessException ignored) {} return result; }}