fastjson 序列化Map< Integer, ?>时,结果的key是数字

mbskvtky  于 4个月前  发布在  其他
关注(0)|答案(1)|浏览(51)

版本

1.2.76

复现代码

Map<Integer, String> data = new HashMap<Integer, String>() {{ put(1, "2"); }};

System.out.println(JSON.toJSONString(data));
// 输出 {1:"2"}

Gson gson = new GsonBuilder().create();
System.out.println(gson.toJson(data, Map.class));
// 输出 {"1":"2"}

ObjectMapper jackson = new ObjectMapper();
System.out.println(jackson.writeValueAsString(data));
// 输出  {"1":"2"}

备注

JSON标准定义中,object的key只能是字符串,规范正文就6页

以下内容节选自 ECMA-404 [1] [2]
6 Objects
An object structure is represented as a pair of curly bracket tokens surrounding zero or more
name/value pairs.
** A name is a string. ** A single colon token follows each name, separating the name from the value. A single comma token separates a value from a following name. The JSON syntax does not impose any restrictions on the strings used as names, does not require that name strings be unique, and does not assign any significance to the ordering of name/value pairs. These are all semantic considerations that may be defined by JSON processors or in specifications defining specific uses of JSON for data interchange

[1] https://www.ecma-international.org/wp-content/uploads/ECMA-404_2nd_edition_december_2017.pdf
[2] https://www.ecma-international.org/publications-and-standards/standards/ecma-404/

pbpqsu0x

pbpqsu0x1#

似乎是个老问题,无法理解为什么一定要加上 SerializerFeature.WriteNonStringKeyAsString 参数才能达到规范格式

相关问题