I've a problem trying to make my page printing out the JSONObject in the order i want. In my code, I entered this:
JSONObject myObject = new JSONObject();
myObject.put("userid", "User 1");
myObject.put("amount", "24.23");
myObject.put("success", "NO");
However, when I see the display on my page, it gives:
JSON formatted string: [{"success":"NO", "userid":"User 1", "bid":24.23}]
I need it in the order of userid, amount, then success. Already tried re-ordering in the code, but to no avail. I've also tried .append....need some help here thanks!!
You cannot and should not rely on the ordering of elements within a JSON object.
From the JSON specification at https://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.
I agree with the other answers. You cannot rely on the ordering of JSON elements.
However if we need to have an ordered JSON, one solution might be to prepare a LinkedHashMap object with elements and convert it to JSONObject.
#Test
def void testOrdered() {
Map obj = new LinkedHashMap()
obj.put("a", "foo1")
obj.put("b", new Integer(100))
obj.put("c", new Double(1000.21))
obj.put("d", new Boolean(true))
obj.put("e", "foo2")
obj.put("f", "foo3")
obj.put("g", "foo4")
obj.put("h", "foo5")
obj.put("x", null)
JSONObject json = (JSONObject) obj
logger.info("Ordered Json : %s", json.toString())
String expectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""
assertEquals(expectedJsonString, json.toString())
JSONAssert.assertEquals(JSONSerializer.toJSON(expectedJsonString), json)
}
Normally the order is not preserved as below.
#Test
def void testUnordered() {
Map obj = new HashMap()
obj.put("a", "foo1")
obj.put("b", new Integer(100))
obj.put("c", new Double(1000.21))
obj.put("d", new Boolean(true))
obj.put("e", "foo2")
obj.put("f", "foo3")
obj.put("g", "foo4")
obj.put("h", "foo5")
obj.put("x", null)
JSONObject json = (JSONObject) obj
logger.info("Unordered Json : %s", json.toString(3, 3))
String unexpectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""
// string representation of json objects are different
assertFalse(unexpectedJsonString.equals(json.toString()))
// json objects are equal
JSONAssert.assertEquals(JSONSerializer.toJSON(unexpectedJsonString), json)
}
You may check my post too: http://www.flyingtomoon.com/2011/04/preserving-order-in-json.html
u can retain the order, if u use JsonObject that belongs to com.google.gson :D
JsonObject responseObj = new JsonObject();
responseObj.addProperty("userid", "User 1");
responseObj.addProperty("amount", "24.23");
responseObj.addProperty("success", "NO");
Usage of this JsonObject doesn't even bother using Map<>
CHEERS!!!
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;
}
}
from lemiorhan example
i can solve with just change some line of lemiorhan's code
use:
JSONObject json = new JSONObject(obj);
instead of this:
JSONObject json = (JSONObject) obj
so in my test code is :
Map item_sub2 = new LinkedHashMap();
item_sub2.put("name", "flare");
item_sub2.put("val1", "val1");
item_sub2.put("val2", "val2");
item_sub2.put("size",102);
JSONArray itemarray2 = new JSONArray();
itemarray2.add(item_sub2);
itemarray2.add(item_sub2);//just for test
itemarray2.add(item_sub2);//just for test
Map item_sub1 = new LinkedHashMap();
item_sub1.put("name", "flare");
item_sub1.put("val1", "val1");
item_sub1.put("val2", "val2");
item_sub1.put("children",itemarray2);
JSONArray itemarray = new JSONArray();
itemarray.add(item_sub1);
itemarray.add(item_sub1);//just for test
itemarray.add(item_sub1);//just for test
Map item_root = new LinkedHashMap();
item_root.put("name", "flare");
item_root.put("children",itemarray);
JSONObject json = new JSONObject(item_root);
System.out.println(json.toJSONString());
JavaScript objects, and JSON, have no way to set the order for the keys. You might get it right in Java (I don't know how Java objects work, really) but if it's going to a web client or another consumer of the JSON, there is no guarantee as to the order of keys.
Download "json simple 1.1 jar" from this https://code.google.com/p/json-simple/downloads/detail?name=json_simple-1.1.jar&can=2&q=
And add the jar file to your lib folder
using JSONValue you can convert LinkedHashMap to json string
For those who're using maven, please try com.github.tsohr/json
<!-- https://mvnrepository.com/artifact/com.github.tsohr/json -->
<dependency>
<groupId>com.github.tsohr</groupId>
<artifactId>json</artifactId>
<version>0.0.1</version>
</dependency>
It's forked from JSON-java but switch its map implementation with LinkedHashMap which #lemiorhan noted above.
As all are telling you, JSON does not maintain "sequence" but array does, maybe this could convince you:
Ordered JSONObject
For Java code, Create a POJO class for your object instead of a JSONObject.
and use JSONEncapsulator for your POJO class.
that way order of elements depends on the order of getter setters in your POJO class.
for eg. POJO class will be like
Class myObj{
String userID;
String amount;
String success;
// getter setters in any order that you want
and where you need to send your json object in response
JSONContentEncapsulator<myObj> JSONObject = new JSONEncapsulator<myObj>("myObject");
JSONObject.setObject(myObj);
return Response.status(Status.OK).entity(JSONObject).build();
The response of this line will be
{myObject : {//attributes order same as getter setter order.}}
The main intention here is to send an ordered JSON object as response. We don't need javax.json.JsonObject to achieve that. We could create the ordered json as a string.
First create a LinkedHashMap with all key value pairs in required order. Then generate the json in string as shown below.
Its much easier with Java 8.
public Response getJSONResponse() {
Map<String, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("A", "1");
linkedHashMap.put("B", "2");
linkedHashMap.put("C", "3");
String jsonStr = linkedHashMap.entrySet().stream()
.map(x -> "\"" + x.getKey() + "\":\"" + x.getValue() + "\"")
.collect(Collectors.joining(",", "{", "}"));
return Response.ok(jsonStr).build();
}
The response return by this function would be following:
{"A":"1","B":"2","C":"3"}
Underscore-java uses linkedhashmap to store key/value for json. I am the maintainer of the project.
Map<String, Object> myObject = new LinkedHashMap<>();
myObject.put("userid", "User 1");
myObject.put("amount", "24.23");
myObject.put("success", "NO");
System.out.println(U.toJson(myObject));
I found a "neat" reflection tweak on "the interwebs" that I like to share.
(origin: https://towardsdatascience.com/create-an-ordered-jsonobject-in-java-fb9629247d76)
It is about to change underlying collection in org.json.JSONObject to an un-ordering one (LinkedHashMap) by reflection API.
I tested succesfully:
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import org.json.JSONObject;
private static void makeJSONObjLinear(JSONObject jsonObject) {
try {
Field changeMap = jsonObject.getClass().getDeclaredField("map");
changeMap.setAccessible(true);
changeMap.set(jsonObject, new LinkedHashMap<>());
changeMap.setAccessible(false);
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
}
[...]
JSONObject requestBody = new JSONObject();
makeJSONObjLinear(requestBody);
requestBody.put("username", login);
requestBody.put("password", password);
[...]
// returned '{"username": "billy_778", "password": "********"}' == unordered
// instead of '{"password": "********", "username": "billy_778"}' == ordered (by key)
Just add the order with this tag
#JsonPropertyOrder({ "property1", "property2"})
Not sure if I am late to the party but I found this nice example that overrides the JSONObject constructor and makes sure that the JSON data are output in the same way as they are added. Behind the scenes JSONObject uses the MAP and MAP does not guarantee the order hence we need to override it to make sure we are receiving our JSON as per our order.
If you add this to your JSONObject then the resulting JSON would be in the same order as you have created it.
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import org.json.JSONObject;
import lombok.extern.java.Log;
#Log
public class JSONOrder {
public static void main(String[] args) throws IOException {
JSONObject jsontest = new JSONObject();
try {
Field changeMap = jsonEvent.getClass().getDeclaredField("map");
changeMap.setAccessible(true);
changeMap.set(jsonEvent, new LinkedHashMap<>());
changeMap.setAccessible(false);
} catch (IllegalAccessException | NoSuchFieldException e) {
log.info(e.getMessage());
}
jsontest.put("one", "I should be first");
jsonEvent.put("two", "I should be second");
jsonEvent.put("third", "I should be third");
System.out.println(jsonEvent);
}
}
Just use LinkedHashMap to keep de order and transform it to json with jackson
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
stats.put("aaa", "aaa");
stats.put("bbb", "bbb");
stats.put("ccc", "ccc");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
System.out.println(json);
maven dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.10.7</version>
</dependency>
I just want the order for android unit tests that are somehow randomly changing overtime with this cool org.json.JSONObject, even thou it looks like it uses linked map but probably depends on api you compile it with or something, so it has different impl. with different android api probably.
I would suggest something like this:
object Json {
#SuppressLint("DiscouragedPrivateApi")
fun Object() = org.json.JSONObject().apply {
runCatching {
val nameValuePairs: Field = javaClass.getDeclaredField("nameValuePairs")
nameValuePairs.isAccessible = true
nameValuePairs.set(this, LinkedHashMap<String, Any?>())
}.onFailure { it.printStackTrace() }
}
}
Usage:
val jsonObject = Json.Object()
...
This is just some possibility I use it little differently so I modified it to post here. Sure gson or other lib is another option.
Suggestions that specification is bla bla are so shortsighted here, why you guys even post it, who cares about 15 years old json spec, everyone wants it ordered anyway.
In an XPages application I have in a sessionScope variable the configuration for the application in JSON format.
I wonder how I can get hold of this configuration again in Java?
I tried:
Map<String, Object> sesScope = ExtLibUtil.getSessionScope();
if (null != sesScope.get("configJSON")){
JsonJavaObject jsonObject = new JsonJavaObject();
jsonObject = (JsonJavaObject) sesScope.get("configJSON");
System.out.println("got object?");
System.out.println("json " + jsonObject.toString());
}
In the console I never get to the "got object?" print statement. What am I doing wrong?
The JavaScript method JSON.parse that you use, returns just a plain simple JavaScript object, not the JsonJavaObject. You can't use JavaScript object later in Java without additional unnecessary overhead. Don't use json2.jss, use JsonParser like Paul Withers have told.
Change your code that gets JSON from your Notes field:
#{javascript:
importPackage(com.ibm.commons.util.io.json);
var jsonText = doc.getItemValueString(itemname);
var jsonFactory:JsonFactory = JsonJavaFactory.instanceEx;
var jsonObject = JsonParser.fromJson(jsonFactory, jsonText);
sessionScope.put('configJSON', jsonObject);
}
Modify your provided java code by removing unnecessary line:
Map<String, Object> sesScope = ExtLibUtil.getSessionScope();
if (null != sesScope.get("configJSON")) {
JsonJavaObject jsonObject = (JsonJavaObject) sesScope.get("configJSON");
System.out.println("got object?");
System.out.println("json " + jsonObject.toString());
}
You should now be OK.
Hint: if you use JsonJavaFactory.instance instead of JsonJavaFactory.instanceEx, you'll get java.util.HashMap instead of JsonJavaObject
Has the sessionScope variable been set? Use sesScope.containsKey("configJSON") to verify. If it's an empty JSON object it will be "{}" rather than null. If you're loading as JSON from a REST service or a Notes Document it may be a String rather than a JsonJavaObject. For parsing a String of JSON, you can use com.ibm.commons.util.io.json.JsonParser. The constructor for JsonJavaObject expects a Map, not sure if this is what's being passed in.
JsonJavaObject is your POJO java class ?
If Yes then please use ObjectMapper of Fasterxml to map your JSON data to the fields of JsonJavaObject class.Use this method to map your json data to any POJO class
public final T validateJson(final Map<String, Object> jsonMap, final T temmplateClass) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
try {
// convert JSON string to Map
String jsonString = objectMapper.writeValueAsString(jsonMap);
return objectMapper.readValue(jsonString, (Class<T>) temmplateClass);
} catch (JsonMappingException e) {
throw new NestableRuntimeException(String.format(ApiCommonConstants.INVALID_JSON_FIELD,
e.getPath().get(e.getPath().size() - 1).getFieldName()));
} catch (IOException e) {
throw new NestableRuntimeException(e.getMessage(), e);
}
}
I'm working on some JSON converting to POJO and the server I'm getting response of is sending a JSON like this:
"Availability":{
"StatusCode":"A",
"BreakDown":{
"2017-10-27":"A"
}
}
How can I save this ( "2017-10-27":"A" )? It changes with each of my request so it should be dynamic! Is it even possible?
If you are going the value currently represented as "2017-10-27":"A", you have to know it is hold in the variable "BreakDown". So you need to query this variable with jsonPath: $.Availability.BreakDown.
it will give this JSON object:
{"2017-10-27":"A"}
Hope it answer your question
The first answer is pretty accurate but to extract the key and value without directly referencing is the target since they are dynamic.
var x = obj.Availability.Breakdown;
for(var key in x){
console.log(key);
console.log(x[key]);
}
This way you get the key and the value both and use it as you like.
Plus, if there are multiple key-value pair inside var x then they can also be reached with this loop.
Assuming that with "should be dynamic" you mean that the content that you want to save (the one inside BreakDown) could change (even the type) for each request and assuming that your example of the json is:
Test.json:
{
"StatusCode":"A",
"BreakDown":{
"2017-10-27":"A"
}
}
You could use the Gson library to get the info that you want. Because every class has Object as a superclass, you could deserialize your json as a Map<Object, Object>.
public static void main(String args[]) {
Gson gson = new Gson();
Map<Object, Object> breakDown=null;
String filename="/.../Test.json";
JsonReader reader = null;
try {
reader = new JsonReader(new FileReader(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final Type type = new TypeToken<Map<Object,Object>>() {}.getType();
Map <Object,Object> conv= gson.fromJson(reader, type);
for (Map.Entry<Object, Object> entry : conv.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
if(entry.getKey().equals("BreakDown"))
{
breakDown= (Map<Object, Object>) entry.getValue();
}
}
if(breakDown!=null){
Map.Entry first= breakDown.entrySet().iterator().next();
System.out.println(first.getKey());
System.out.println(first.getValue());
}
}
The Map<Object, Object> breakDown map is also of Objects because I'm assuming that the key and the value could be different of the example that you posted. Otherwise, if the key is always a date and the value a string, can be defined as Map<Date, String> breakDown.
How can I parse a key-value pair which I know is result of toString() method of a LinkedTreeMap (it's in some inaccessible code) to a LinkedTreeMap<String, Object>?
Sample string which I would like to convert to : LinkedTreeMap<String, Object>
{Path=z.jpg.json, ImageProperties={Owner=Jack, ImageQuality=6}}
Also I would be happy if I can convert it JSON
You can transform your toString() value to JSON format:
String toStringValue = "{Path=z.jpg.json, ImageProperties={Owner=Jack, ImageQuality=6}}";
String jsonValue = toStringValue.replace("{","{\").replaceAll(",\\s+","\", \"").replace("=","\":\"").replace("}","\"}");
and then this string could be parsed by any json parser.
I m not sure what exactly you want. But I think you can make use of something like thisnew JSONObject(map); .Also please elaborate with some input and output if this doesn't help
I found this method which converts key-value string to JSON, recursively:
public static JSONObject convertKeyValueToJSON(LinkedTreeMap<String, Object> ltm) {
JSONObject jo=new JSONObject();
Object[] objs = ltm.entrySet().toArray();
for (int l=0;l<objs.length;l++)
{
Map.Entry o= (Map.Entry) objs[l];
try {
if (o.getValue() instanceof LinkedTreeMap)
jo.put(o.getKey().toString(),convertKeyValueToJSON((LinkedTreeMap<String, Object>) o.getValue()));
else
jo.put(o.getKey().toString(),o.getValue());
} catch (JSONException e) {
e.printStackTrace();
}
}
return jo;
}