序列化LinkedHashMap,有序输出Json字符串

LinkedHashMap本身是有序的,使用JDK自带的序列化代码或者fastJson代码序列化后,字符串并非按照插入顺序输出

Map linkedMap=new LinkedHashMap();
linked2.put("b","2");
linked2.put("a","1");
linked2.put("c","3");
String jsonStr=JSON.toJSONString(linkedMap);
输出jsonStr为{"a":"1","b":"2","c":"3"}
解决办法:
使用
Gson(com.google.gson)序列化
Map linkedMap=new LinkedHashMap();
linked2.put("b","2");
linked2.put("a","1");
linked2.put("c","3");
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
String jsonStr=gson.toJson(linked2);
System.out.println(jsonStr);
输出jsonStr为{"b":"2","a":"1","c":"3"}
 


 

转载于:https://www.cnblogs.com/hujiapeng/p/5065909.html

你可能感兴趣的:(序列化LinkedHashMap,有序输出Json字符串)