Priyansh Goel Priyansh Goel - 6 months ago 44
JSON Question

Getting key in sequence/order in JSONObject JAVA

I am trying to make a JSON document like this :

{
"query": {
"bool":{
"must":{
"match": {
"action": "HI"
},
"filter":{
"range":{
"epoch": {
"gte" : "1454964688008"
}
}
}
}
}
}


}

The condition is that match should always be before the filter JSONObject.

SO , seeing from this thread, I implemented something like this:

public static String getQuery(Alert reqAlert) {


LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Serializable>>>>> main = new LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Serializable>>>>>();
LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Serializable>>>> query = new LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Serializable>>>>();
LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Serializable>>> bool = new LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Serializable>>>();
LinkedHashMap<String, LinkedHashMap<String, Serializable>> must = new LinkedHashMap<String, LinkedHashMap<String, Serializable>>();
LinkedHashMap<String, Serializable> match = new LinkedHashMap<String, Serializable>();
LinkedHashMap<String, Serializable> filter = new LinkedHashMap<String, Serializable>();
LinkedHashMap<String, LinkedHashMap<String, String>> range = new LinkedHashMap<String, LinkedHashMap<String, String>>();
LinkedHashMap<String, String> epoch = new LinkedHashMap<String, String>();
epoch.put("gte", "1454964688008");
range.put("epoch", epoch);
filter.put("range", range);
match.put("action", reqAlert.getQueryString());
must.put("match", match);
must.put("filter", filter);
bool.put("must", must);
query.put("bool", bool);
main.put("query", query);


JSONObject mainObject = new JSONObject(main);

return mainObject.toString();
}


But it always print

{"query":{"bool":{"must":{"filter":{"range":{"epoch":{"gte":"1454964688008"}}}},"match":{"action":"HI"}}}}


What should I do?

Answer

So that if somebody also has the same requirement, The best way to do it use a JSONObject from the following maven dependency.

       <dependency>
            <groupId>org.codehaus.jettison</groupId>
            <artifactId>jettison</artifactId>
            <version>1.3.5</version>
        </dependency>

Jettison uses LinkedHashMap internally.