alibaba / alibaba/fastjson2

[BUG]通过ObjectReader定制反序列化后,其所对应的类型无法再使用JSONObject.to(...) 与 JSONObject.getObject(...) 方法

Open
#3,901 8 comments 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

### 问题描述
通过 ObjectReader 定制反序列化后,其所对应的类型无法再使用JSONObject.to(...) 与 JSONObject.getObject(...) 方法,必定抛出异常

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

- OS信息: [Mac OS 15.3.2]
- JDK信息: [jdk 1.8.0_312]
- 版本信息:[Fastjson2 2.0.60]

### 重现步骤
运行如下代码重现:

```java
public class UserReader implements ObjectReader {
public Object readObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) {
// 这里返回 user 仅为示例,JSONObject.to(...) 不会走到这里
return new User();
}
}

public class User {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

public class FastJsonTest {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "James");

// 未注册 UserReader 之前功能正常
User user = jsonObject.to(User.class);

// 注册 UserReader
JSON.register(User.class, new UserReader());

// 注册后得先转成 String 才能使用 JSONObject.to(...)、JSONObject.getObject()
user = JSON.parseObject(jsonObject.toJSONString(), User.class);

// 注册后 JSONObject.to(...)、JSONObject.getObject() 都将无法使用
user = jsonObject.to(User.class);

System.out.println(user.getName());
}
}
```

### 代码说明
只要 JSON.register(User.class, new UserReader()) 注册了 ObjectReader 定制反序列化实现,JSONObject.to(...) 与JSONObject.getObject() 就一定用不了。

但通过 JSONObject.toJSONString() 将先数据转成 json string,再通过 JSON.parseObject(...) 转换为 bean 是可以实现的。

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the failure through JSONObject.to(...) and JSONObject.getObject(...) after JSON.register(User.class, new UserReader()), then trace the conversion path used by these APIs. Compare it with the working JSON.parseObject(...) path; done means both JSONObject methods still convert the registered type successfully without a string round-trip.

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
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.