[BUG] 泛型嵌套时 `JSON.parseObject` 解析类型错误
- Dominant language
- Java
- Stars
- 4.4k
- Forks
- 613
- Avg merge
- 1d 22h
- Merged PRs (30d)
- 6
Description
### 问题描述
当泛型嵌套使用时,使用 `JSON.parseObject` 搭配 `TypeReference` 解析 JSON 时忽略错误地泛型信息。
但是这个问题我无法在其它位置复现,我把代码复制出来之后,虽然代码一模一样,但是执行出来的结果就不一样了。
### 环境信息
*请填写以下信息:*
- OS信息:Mac OS Sequoia 15.3.1 (2.6 GHz 六核Intel Core i7 + 16G)
- JDK信息:Graalvm 21.0.6
- 版本信息:Fastjson2 2.0.57
### 重现步骤
1. 执行 `test` 方法
2. 观察 `obj` 的值
```kotlin
fun test() {
// if (event.type === CoreLifeCycleEnum.AFTER_INIT) {
val text = "{\"data\":{\"outputs\":{\"errno\":0,\"data\":\"test\",\"msg\":\"ok\"}}}"
val type = TypeReference.parametricType(
DifyResponseBody::class.java,
DifyDocBuilder::class.java
)
val obj = JSON.parseObject>(text, type)
// 这里 `obj.data.outputs` 的类型是 `JSONObject`,实际应当是 DifyDocBuilder`。
println(obj)
// }
}
data class DifyResponseBody(
val data: DifyResponseData,
)
data class DifyResponseData(
val outputs: T,
)
data class DifyDocBuilder(
val errno: Int,
val msg: String,
val data: String?,
)
```
在调用 `JSON.parseObject` 中,在下图的位置,`outputs`的类型还是正确的:


但是在执行 `creatorFunction.apply` 时,出现了问题,`paramType` 的泛型参数变成了 `T`,然后 `outputs` 就被 `cast` 转换为了 `JSONObject`:


我把我的代码单独拿出来跑到时候,并没有进入到 `ObjectReaderNoneDefaultConstructor` 这个类中执行,而是动态生成了一个类来解析 json,结果是正确的。
Contributor guide
Research direction
Start with JSON.parseObject, TypeReference.parametricType, and the ObjectReaderNoneDefaultConstructor path described in the report, then inspect where creatorFunction.apply receives the nested generic parameter. Reproduce the Kotlin example and verify that obj.data.outputs is created as DifyDocBuilder rather than JSONObject.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java, kotlin
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100