Home > Article > Web Front-end > How to implement single-layer json sorting in alphabetical order by key (detailed tutorial)
The editor below will share with you an example of how to sort single-layer json in alphabetical order by key. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor and take a look.
I recently encountered a problem when working on a bank project: the bank’s signature data must be arranged in order, and then spliced together to add the signature. At this time, I encountered a problem, how to implement it The key-value in the JSONObject object is sorted according to key;
The implementation code is as follows:
import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;
import net.sf.json.JSONObject;
public class JsonUtils {
/**
* 对单层json进行key字母排序
* @param json
* @return
*/
public static JSONObject getSortJson(JSONObject json){
Iterator iteratorKeys = json.keys();
SortedMap map = new TreeMap();
while (iteratorKeys.hasNext()) {
String key = iteratorKeys.next().toString();
String vlaue = json.optString(key);
map.put(key, vlaue);
}
JSONObject json2 = JSONObject.fromObject(map);
return json2;
}
public static void main(String[] args){
JSONObject json = new JSONObject();
json.put("cc", "cc");
json.put("bb", "bb");
json.put("ee", "ee");
json.put("aa", "aa");
json.put("ba", "ba");
json.put("bd", "bd");
System.out.println(getSortJson(json).toString());
}
}
The above is what I compiled for everyone. I hope that in the future It will be helpful to everyone.
Related articles:
How to create a complete project process using gulp
##How to add an array to an object in js
How to dynamically control page elements in jQuery
The above is the detailed content of How to implement single-layer json sorting in alphabetical order by key (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!