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 ??
The JSON standard defines objects as "an unordered collection of zero or more name/value pairs". As such, an implementation does not need to preserve any specific order of object keys.
Any error or exception? The JSON RFC (RFC 4627) says that order of object members does not matter.
JSONObject is "native" to Android SDK, JsonObject is probably the one from Gson library, the one that I use. Two different package, don't work with both ;) choose one. I had some issue with the date formatting in JSONObject.
JsonObject class represents an immutable JSON object value (an unordered collection of zero or more name/value pairs). It also provides unmodifiable map view to the JSON object name/value mappings. A JsonObject instance can be created from an input source using JsonReader. readObject() .
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.
as others have mentioned, JSONObject isn't supposed to keep the same order.
however, if you do wish to have ordered items, you can implement it yourself, and use LinkedHashMap as the container of items for your class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With