alibaba / alibaba/fastjson2

[BUG] 指定JSONWriter.Feature.WriteClassName在输出有”Set[]“内容的时候反序列化会报错

Open
#2,953 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

### 问题描述
*简要描述您碰到的问题。*

```
public class A {
...
Map map;// 存储了B对象
}

public class B {
...
Set set;
}
```

项目1 中使用 `String jsonString = JSON.toJSONString(xxx, JSONWriter.Feature.WriteClassName)` 序列化为带有类名的 json,本项目中`JSON.parseObject(jsonString, xxx.class, JSONReader.Feature.SupportAutoType);` 能够正常解析。

在 项目2(项目2中没有 B类型对应的java文件)中使用 项目1 中序列化结果进行反序列化 `JSON.parseObject(jsonString, xxx.class, JSONReader.Feature.SupportAutoType);` 或`JSON.parseObject(jsonString, xxx.class);` 都无法解析,因为B.class有Set类型的字段,导致`jsonString`中出现了类似`"userList":Set[]`这样的内容,所以解析报错了,通过 `jsonString.replace("Set[]", "[]")`处理后,则能够正常兼容解析(项目2中没有对应类文件的B对象被处理为`JSONObject`对象)。

### 环境信息

- JDK信息: [e.g.:Openjdk 1.8.0_312]
- 版本信息:[e.g.:Fastjson2 2.0.15]

### 期待的正确结果

能否提供一个额外的注解,在未指定Feature.WriteClassName时,支持被注解的某个类的指定字段或某个被注解了的指定类型才额外输出"@type"记录的类名?
这样在反序列化时,在不同的项目中能够兼容处理同一个json。

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the failure through JSON.toJSONString with JSONWriter.Feature.WriteClassName and JSON.parseObject with JSONReader.Feature.SupportAutoType, using a Set field and a missing B class. Investigate how Set[] is emitted and parsed; done should include a defined compatibility behavior for projects without B and tests covering the proposed annotation or serialization change.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.