Home > Web Front-end > JS Tutorial > How to implement single-layer json sorting in alphabetical order by key (detailed tutorial)

How to implement single-layer json sorting in alphabetical order by key (detailed tutorial)

亚连
Release: 2018-06-22 15:28:58
Original
4141 people have browsed it

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:

<span style="font-size:18px;">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<String> 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()); 
 } 
}</span>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template