JSONObject : Why JSONObject changing the order of attributes
java, json
Solution
See the answer here: JSON order mixed up
You cannot and should not rely on the ordering of elements within a JSON object.
From the JSON specification at http://www.json.org/:
"An object is an unordered set of name/value pairs"
As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.
Problem
I was trying to construct an JSON String using JSON Object I want the JSON String to be constructed this way ``` { "Level": "3", "Name": "testLogger", "IPADDRESS": "testMachiene", "Message": "hiiiiiiiiii", "TimeStamp": "test12345678" } ``` This is my simple program to do so ``` package com; import org.json.JSONObject; public class Teste { public static void main(String args[]) throws Exception { int loglevel = 3; String loggerName = "testLogger"; String machieneName = "testMachiene"; String timeStamp = "test12345678"; String message = "hiiiiiiiiii"; JSONObject obj = new JSONObject(); obj.put("TimeStamp", message); obj.put("Message", timeStamp); obj.put("IPADDRESS", machieneName); obj.put("Name", loggerName); obj.put("Level", loglevel); System.out.println(obj.toString()); } } ``` And it was constructing this way ``` { "Name": "testLogger", "TimeStamp": "hiiiiiiiiii", "Message": "test12345678", "Level": 3, "IPADDRESS": "testMachiene" } ``` My question is that why its changing the order of attributes Can i have the order in which i wish ??