[alibaba/fastjson]一个关于排序很明显的bug

2025-11-03 118 views
6
    Map<String, String> testMap = new HashMap<>();
    testMap.put("a", "1");
    testMap.put("b", "2");
    testMap.put("symbol", "3");

    System.out.println(JSON.toJSONString(testMap, SerializerFeature.SortField));

输出结果:

{"a":"1","symbol":"3","b":"2"}

很明显json串中如果包含symbol这个字符,排序就懵了。会发生意想不到的排序结果,可以实验下: asymbol asymbola Symbol等都不能正确排序

在延伸:

Map<String, String> testMap = new HashMap<>(); testMap.put("a", "1"); testMap.put("cmjjjjl", "2"); testMap.put("ca", "3");

    System.out.println(JSON.toJSONString(testMap, SerializerFeature.SortField));

这要是有问题的。 fastjson的 SerializerFeature.SortField还是避免使用把它是有问题的!

回答

0

特性越多,问题越多,最近深度使用的时候已经发现这样类似的问题多个。 能力越大,责任越大~ 希望作者能及时修复,把这个库做的越来越好。

2

HashMap 本身是无序的,换成 LinkedHashMap试试。

6

这样就可以了

JSON.toJSONString(testMap, SerializerFeature.MapSortField)
0

SerializerFeature.MapSortField 就可以了,就是老版本没这个。 SerializerFeature.SortField似乎只能对实体字段进行排序?

2

LinkedHashMap

正解