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"}