I'm getting JSON, but it's not in alphabetical order. How to sort json by it's KEY ?
JSON:
{"b":"3","c":"1","a":"4"}
Expected output:
{"a":"4","b":"3","c":"1"}
Please help me to solve this problem. I really appreciate your help! Thanks!
I'm getting JSON, but it's not in alphabetical order. How to sort json by it's KEY ?
JSON:
{"b":"3","c":"1","a":"4"}
Expected output:
{"a":"4","b":"3","c":"1"}
Please help me to solve this problem. I really appreciate your help! Thanks!
You can use the jackson library.
First add a jackson to the maven dependency.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
Then use the code below.
String jsonData = "{\"e\":\"6\",\"f\":\"1\",\"b\":\"3\",\"c\":\"1\",\"a\":\"4\"}";
ObjectMapper om = new ObjectMapper();
om.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
Map<String, Object> map = om.readValue(jsonData, HashMap.class);
String json = om.writeValueAsString(map);
System.out.println(json); // result : {"a":"4","b":"3","c":"1","e":"6","f":"1"}
When I test it, I get output in sorted form.
{"a":"4","b":"3","c":"1","e":"6","f":"1"}
So here is one of solution to sort JSON object by key alphabetically without using external libraries(for Android Studio). The sortedJSON is the one with key sorted alphabetically.
try{
JSONObject jo = new JSONObject();
jo.put("g", "9");
jo.put("t", "8");
jo.put("r", "7");
jo.put("d", "6");
jo.put("c", "5");
jo.put("b", "4");
jo.put("a", "1");
Map<String, String> joToMap = new HashMap<>();
Iterator<String> keysItr = jo.keys();
while (keysItr.hasNext()) {
String key = keysItr.next();
Object value = jo.get(key);
joToMap.put(key, value.toString()); //since value is string so convert toString; depend on your value type
}
Map<String, String> sortedMap = new TreeMap<>(joToMap); //this will auto-sort by key alphabetically
JSONObject sortedJSON = new JSONObject(); //recreate new JSON object for sorted result
for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
sortedJSON.put(entry.getKey(), entry.getValue());
// result will be {"a":"1","b":"4","c":"5","d":"6","g":"9","r":"7","t":"8"}
}
} catch (Exception e){
}
You can use maps for this purpose , then sort the map according to the map key. after that insert it into the JSON object.
In your case declare the map as:
Map<String,Integer> mapName = new HashMap<>();