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

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

Map<String,String> linkedMap=new LinkedHashMap<String,String>();
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<String,String> linkedMap=new LinkedHashMap<String,String>();
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"}
 


 
posted @ 2015-12-22 10:44  jiapeng  阅读(6199)  评论(0编辑  收藏  举报