fastjson 1.2.58,toJSONString(Object)生成了非标准JSON

n8ghc7c1  于 4个月前  发布在  其他
关注(0)|答案(6)|浏览(64)
Map<Integer, Object> map = new HashMap<>();
map.put(12, new ArrayList<>());
map.put(34, new ArrayList<>());
System.out.println(JSON.toJSONString(map));
//输出: {34:[],12:[]}

其中输出json的key不是String类型,造成生产环境损失
建议在下一个版本,将 SerializerFeature.WriteNonStringKeyAsString 设置为默认

jfewjypa

jfewjypa1#

这个目前有对应的参数吗?

bwntbbo3

bwntbbo32#

String s = JSON.toJSONString(map, SerializerFeature.WriteNonStringKeyAsString);

zi8p0yeb

zi8p0yeb3#

@zhulc0914
你可以在程序入口处设置全局化配置,这样就不用在每个toJSONString设置feature
JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.WriteNonStringKeyAsString.getMask();

但我认为作为通用组件产生非标准的JSON串是不科学的···

8ehkhllq

8ehkhllq4#

1.2.36 及以下版本都是标准的 json,升级以后变了变了。

fgw7neuy

fgw7neuy5#

@wenshao
温先生好,我看到 com.alibaba.fastjson.JSON#DEFAULT_GENERATE_FEATURE 被静态代码块初始化,所以 JSON.DEFAULT_GENERATE_FEATURE 已经包含了一些缺省配置。
可否在下个迭代中加入 SerializerFeature.WriteNonStringKeyAsString 的缺省配置吗?
感谢!

public static int DEFAULT_GENERATE_FEATURE;
    static {
        int features = 0;
        features |= SerializerFeature.QuoteFieldNames.getMask();
        features |= SerializerFeature.SkipTransientField.getMask();
        features |= SerializerFeature.WriteEnumUsingName.getMask();
        features |= SerializerFeature.SortField.getMask();
        /*默认序列化为标准JSON*/
        features |= SerializerFeature.WriteNonStringKeyAsString.getMask();
        DEFAULT_GENERATE_FEATURE = features;
    }
0ejtzxu1

0ejtzxu16#

RFC 4627 An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

Deserialization errors may occur if the name is not a string, such as using Jackson or PHP, C# or other languages

相关问题