map序列化成json对象传递给前端时,map中属性的顺序会按首字母重新排序
json对象中的属性没有顺序而言,一次序列化、反序列化就会乱。
试过把map转成了JSON字符串,传给前端,还是不行
JSON.parseObject(JSON.toJSONString(contractsFactorMap),new TypeReference<TreeMap<String, String>>(){} , Feature.OrderedField)
想到数组可以保证顺序,可以把后端的map转成List数组,这样序列化成json不会影响顺序。
@Service
public class ComponentsContants {
/**
* @description: Map转成List数组 (Map只有一层的情况)
* @param:
* @return:
* @author ywx9031
* @date: 2023/10/7 16:59
*/
public static List<Map<String, Object>> MaptoList(Map map) {
List<Map<String, Object>> valueList = new ArrayList<Map<String, Object>>();
Iterator<String> iter = map.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
String value = (String) map.get(key);
Map<String, Object> mapList = new HashMap<String, Object>();
mapList.put("key", key);
mapList.put("value", value);
valueList.add(mapList);
}
return valueList;
}
/**
* @description: Map有2层的情况(Map中还包含map)
* @param:
* @return:
* @author ywx9031
* @date: 2023/11/13 15:45
*/
public static List<Map<String, Object>> MaptoList2(Map map) {
List<Map<String, Object>> valueList = new ArrayList<Map<String, Object>>();
List<Map<String, Object>> valueList1 = new ArrayList<Map<String, Object>>();
Iterator<String> iter = map.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
Map<String, Object> mapList = new HashMap<String, Object>();
mapList.put("key", key);
Map map1 = (Map) map.get(key);
Iterator<String> iter1 = map1.keySet().iterator();
while (iter1.hasNext()) {
String key1 = iter1.next();
Map<String, Object> mapList1 = new HashMap<String, Object>();
mapList1.put("key", key1);
mapList1.put("value", map1.get(key1));
valueList1.add(mapList1);
}
mapList.put("value", valueList1);
valueList.add(mapList);
}
return valueList;
}
}
本文转载自: https://blog.csdn.net/weixin_43211480/article/details/134383003
版权归原作者 Evan Yi 所有, 如有侵权,请联系我们删除。
版权归原作者 Evan Yi 所有, 如有侵权,请联系我们删除。