[BUG]为接口(或父类)注册ObjectWriter,不会对该接口(或父类)的子类生效
- Dominant language
- Java
- Stars
- 4.4k
- Forks
- 613
- Avg merge
- 1d 22h
- Merged PRs (30d)
- 6
Description
### 问题描述
*为接口(父类)注册ObjectWriter,不会对该接口(父类)的子类生效。*
### 环境信息
*请填写以下信息:*
- OS信息: Win10
- JDK信息: Java11
- 版本信息:fastjson 2.0.21
### 重现步骤
*使用如下代码复现问题*
```java
public class Fastjson2Test {
interface Animal {
String getName();
boolean isAlive();
}
static class Dog implements Animal {
@Override
public String getName() {
return "dog";
}
@Override
public boolean isAlive() {
return true;
}
}
static class AnimalWriter implements ObjectWriter {
@Override
public void write(JSONWriter jsonWriter, Object value, Object name, Type type, long l) {
if (!(value instanceof Animal)) {
throw new IllegalArgumentException();
}
Animal animal = (Animal) value;
jsonWriter.writeString(animal.getName());
}
}
public static void main(String[] args) {
AnimalWriter animalWriter = new AnimalWriter();
Map target = new HashMap<>();
target.put("animal", new Dog());
// 异常情况:为`Animal`类注册ObjectWriter后,序列化时不会使用该Writer
JSON.register(Animal.class, animalWriter);
String json1 = JSON.toJSONString(target);
System.out.println(json1);
// 正常情况:为`Dog`类注册ObjectWriter后,序列化时该Writer生效
JSON.register(Dog.class, animalWriter);
String json2 = JSON.toJSONString(target);
System.out.println(json2);
// 另外:ObjectReader【不会】出现该问题
}
}
```
- 期望结果
```
{"animal":"dog"}
{"animal":"dog"}
```
- 实际结果
```
{"animal":{"alive":true,"name":"dog"}}
{"animal":"dog"}
```
### 期待的正确结果
*期望为父类(或接口)注册ObjectWriter后,该Writer对子类依然有效*
Contributor guide
Research direction
The entry points named are JSON.register, JSON.toJSONString, and ObjectWriter; start by tracing how a registered Animal writer is looked up when the value is Dog. Use the supplied Fastjson2Test reproduction and compare interface or parent registration with direct Dog registration. Done means the Animal writer is used for Dog values while preserving the existing direct-registration behavior.
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
- Clearly specified
- Newbie friendliness
- 48/100