import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import com.alibaba.fastjson.JSON;
public class TestSortJson {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String jsonmsg="{\"name\":\"yjc\",\"age\":25,\"sex\":\"男\"}";
Map<String,String> map = JSON.parseObject(jsonmsg,Map.class);
Map<String, String> resultMap = sortMap(map);
String result = JSON.toJSONString(resultMap);
System.out.println(result);
}
public static Map<String, String> sortMap(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, String> sortMap = new TreeMap<String, String>(new MapComparator());
sortMap.putAll(map);
return sortMap;
}
}
class MapComparator implements Comparator<String>{
@Override
public int compare(String str1, String str2) {
// TODO Auto-generated method stub
return str1.compareTo(str2);
}
}
缺点:只能比较最外层的字段,如果json里面还有第二层第三层,则里面不能排序,因为这个方法主要是利用treemap里面的key来排序的。