alibaba / alibaba/fastjson2

[BUG] fastjson1 兼容模式下 getJSONArray().toArray() 元素为 com.alibaba.fastjson2.JSONObject,强转 com.alibaba.fastjson.JSONObject 抛 ClassCastException

Open
#7,765 0 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

问题描述
项目从 fastjson 1.x 升级到 fastjson2(仍使用 com.alibaba.fastjson 兼容包/兼容 API)后,对同样的代码,getJSONArray(key).toArray() 返回的元素运行时类型变成了 com.alibaba.fastjson2.JSONObject,而不是 com.alibaba.fastjson.JSONObject。原本在 1.x 下正常的 (com.alibaba.fastjson.JSONObject) element 强转代码,升级后抛出 ClassCastException。

环境信息
OS信息: Windows 11
JDK信息: 1.8.0_211
版本信息:com.alibaba:fastjson:2.0.63(fastjson2 的 fastjson1 兼容包)
重现步骤
用 com.alibaba.fastjson.JSON.parseObject(...) 解析 JSON
对某个数组字段调用 getJSONArray(key).toArray(),取 elements[0]
elements[0] 的运行时类型为 com.alibaba.fastjson2.JSONObject;若按 1.x 代码强转 (com.alibaba.fastjson.JSONObject) elements[0],抛 ClassCastException

package com.example.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class FastJsonDemo {
public static void main(String[] args) {
a();
System.out.println("-----------------------------------------------");
b();
}

// "items" 是以字符串形式存放的 JSON 数组
private static void a() {
String json = "{\"items\":\"[{\\\"name\\\":\\\"alpha\\\"},{\\\"name\\\":\\\"beta\\\"}]\"}";
System.out.println(json);
JSONObject obj = JSON.parseObject(json);
Object[] elements = obj.getJSONArray("items").toArray();
System.out.println(elements[0]);
System.out.println(elements[0].getClass().getName());
}

// "items" 是真正的 JSON 数组
private static void b() {
String json = "{\"items\":[{\"name\":\"alpha\"},{\"name\":\"beta\"}]}";
System.out.println(json);
JSONObject obj = JSON.parseObject(json);
Object[] elements = obj.getJSONArray("items").toArray();
System.out.println(elements[0]);
System.out.println(elements[0].getClass().getName());
}
}
期待的正确结果
使用 com.alibaba.fastjson 兼容 API 时,getJSONArray(...).toArray() 的元素类型应与 fastjson 1.x 保持一致(即 com.alibaba.fastjson.JSONObject),使从 1.x 迁移过来的 (com.alibaba.fastjson.JSONObject) 强转代码继续可用;若这是预期行为,希望在兼容说明文档里明确该差异及推荐写法。

Image

Contributor guide

Open the contributing guide

Research direction

Start by running the supplied FastJsonDemo with fastjson 2.0.63 and inspect the runtime classes returned by getJSONArray("items").toArray() through the fastjson1 compatibility API. Compare both string-encoded and native array cases; done means the compatibility behavior is resolved or the documented difference and recommended migration usage are clear.

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
Quiet
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.