1、引入依赖
com.google.code.gson gson 2.8.2
2、实现
import java.util.Comparator;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;import java.util.TreeMap;import com.google.gson.Gson;import com.google.gson.JsonArray;import com.google.gson.JsonElement;/** * 排序工具 * @ClassName: SortUtils * @Description: * @author weiyb */public class SortUtils{ /** * 获取有序字符串 * @param object * @return * @author weiyb */ public static String getSortParamsByObject(Object object) { Gson g = new Gson(); JsonElement e = g.toJsonTree(object); sort(e); return g.toJson(e); } private static ComparatorgetComparator() { Comparator c = new Comparator () { public int compare(String o1, String o2) { return o1.compareTo(o2); } }; return c; } public static void sort(JsonElement e) { if (e.isJsonNull()) { return; } if (e.isJsonPrimitive()) { return; } if (e.isJsonArray()) { JsonArray a = e.getAsJsonArray(); for (Iterator it = a.iterator(); it.hasNext();) { sort(it.next()); } return; } if (e.isJsonObject()) { Map tm = new TreeMap (getComparator()); for (Entry en : e.getAsJsonObject().entrySet()) { tm.put(en.getKey(), en.getValue()); } for (Entry en : tm.entrySet()) { e.getAsJsonObject().remove(en.getKey()); e.getAsJsonObject().add(en.getKey(), en.getValue()); sort(en.getValue()); } return; } }}
3、测试
import org.junit.Test;import com.alibaba.fastjson.JSON;/** * @ClassName: SignTest * @Description: * @author weiyb * @date 2018年4月10日 下午8:24:30 */public class SortTest { @Test public void sortTest() { User user=new User("1","张三",12); String content = SortUtils.getSortParamsByObject(user); System.out.println(JSON.toJSONString(content)); }}class User{ private String id; private String name; private int age; public User(String id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}