alibaba / alibaba/fastjson2

[BUG] com.alibaba.fastjson.JSONObject.toJSON 方法转换中对于 HashMap<Integer, String> 未向前兼容

Open
#3,849 1 comment 0 reactions 0 assignees View on GitHub
bug
Dominant language
Java
Stars
4.4k
Forks
613
Avg merge
1d 22h
Merged PRs (30d)
6

Description

### 问题描述
在 2.0.58 及以后版本中
HashMap 对象在使用 JSONObject.toJSON(map) 方法 无法正确转换。

### 环境信息
*请填写以下信息:*

- OS信息: [e.g.:CentOS 8.4.2105 4Core 3.10GHz 16 GB]
- JDK信息: [e.g.:Openjdk 1.8.0_312]
- 版本信息:[e.g.:Fastjson2 2.x.x]

### 重现步骤

```
import com.alibaba.fastjson.JSONObject;

HashMap map = new HashMap<>();
map.put(1, "1");
map.put(2, "2");
System.out.println(JSONObject.toJSON(map));

```
在 com.alibaba.fastjson 2.0.57 中可以正常执行并打印
```
{1:"1",2:"2"}
```
但是在 com.alibaba.fastjson 2.0.58 及以后的版本后
会抛出异常
```
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at com.alibaba.fastjson.JSON.adaptResult(JSON.java:2329)
at com.alibaba.fastjson.JSON.adaptResult(JSON.java:2318)
at com.alibaba.fastjson.JSON.toJSON(JSON.java:2311)
at org.example.Main.main(Main.java:16)
```

定位到是 Submit:23ac0978 Fix 3185 (#3593 提交修改增加
``private static Object adaptResult(Object result, int level)``
在针对 fastjson2转换为 fastjson 对象时未对 对象进行安全转换。

相关代码:
```
if (result instanceof com.alibaba.fastjson2.JSONObject) {
JSONObject jsonObject = new JSONObject();
com.alibaba.fastjson2.JSONObject object = (com.alibaba.fastjson2.JSONObject) result;
for (Map.Entry entry : object.entrySet()) {
jsonObject.put(entry.getKey(), adaptResult(entry.getValue(), level + 1)); // entry.getKey() 在上述案例中为Integer 类型
}
return jsonObject;
}
```

### 期待的正确结果

期望版本可以尽量向前兼容。

#### 附加信息
*如果你还有其他需要提供的信息,可以在这里填写(可以提供截图、视频等)。*

Contributor guide

Open the contributing guide

Research direction

Start with JSON.java at adaptResult, especially the JSONObject conversion path identified in the report. Reproduce the supplied JSONObject.toJSON call with HashMap on the affected versions, then add a regression test that captures the intended backward-compatible result and confirms the ClassCastException no longer occurs.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.