alibaba / alibaba/fastjson2

[BUG] record类型TypeReference不起作用,泛型失效。

Open
#3,156 14 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

### 问题描述
*record类型TypeReference不起作用,泛型失效。*

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

- OS信息: [e.g.:win11 i7 12Core 3.10GHz 32GB]
- JDK信息: oracle jdk 21
- 版本信息:[e.g.:Fastjson2 3.5.3]

### 重现步骤
*如何操作可以重现该问题:*

1. 使用 `xxx.xxx` 方法
2. 输入 `...` 数据
3. 出现 `...` 错误

```java
public record AjaxResult(int code, String msg, T data) {}

//public class AjaxResult {
// private int code;
// private String msg;
// private T data;
//
// public AjaxResult() {
// }
//
// public int getCode() {
// return code;
// }
//
// public AjaxResult setCode(int code) {
// this.code = code;
// return this;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public AjaxResult setMsg(String msg) {
// this.msg = msg;
// return this;
// }
//
// public T getData() {
// return data;
// }
//
// public AjaxResult setData(T data) {
// this.data = data;
// return this;
// }
//}

```

```java
public class LoginResult {
private Long userId;
private String name;
}
```

```java
public class TestJsonRecord {
static String json = """
{
"code": 200,
"data": {
"userId": 1524231,
"name": "张三"
}
}
""";

public static void main(String[] args) {
AjaxResult loginResultAjaxResult = JSON.parseObject(json, new TypeReference>() {
});
System.out.println("loginResultAjaxResult = " + loginResultAjaxResult.data().getClass().getName());
}
}

```

### 期待的正确结果
输出loginResultAjaxResult 里面data字段的类型,

如果是使用record就会报错,如果使用注释的用法就会正常输出类名,使用record,里面的泛型信息丢失,被反序列化JsonObject

### 相关日志输出
Exception in thread "main" java.lang.ClassCastException: class com.alibaba.fastjson2.JSONObject cannot be cast to class LoginResult (com.alibaba.fastjson2.JSONObject and LoginResult are in unnamed module of loader 'app')
at TestJsonRecord.main(TestJsonRecord.java:24)

#### 附加信息

![bcfc173c-0957-4b49-9e17-297ac540392e](https://github.com/user-attachments/assets/f4544d9a-8417-435e-8165-3036b2ca51a1)

Contributor guide

Open the contributing guide

Research direction

Start with the TestJsonRecord example and run JSON.parseObject using TypeReference>. Compare the record and commented class cases, then trace how the record's generic data type is handled. Done means the record form deserializes data as LoginResult instead of JSONObject and avoids the ClassCastException shown at TestJsonRecord.java:24.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.