-
Notifications
You must be signed in to change notification settings - Fork 541
Closed
Labels
Milestone
Description
问题描述
实现了List的泛型类MyList,自定义了ObjectReader,当作为getter/setter字段反序列化时,无法调用自定义的ObjectReader,导致反序列化出来的对象MyList的元素类型是JSONObject,但是作为public字段,或者先转换为JSONObject再使用to(Class clazz)方法时正常。
环境信息
- OS信息: Windows11 Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
- JDK信息:Openjdk 11.0.5
- 版本信息:Fastjson2 2.0.57
重现步骤
附件中附带了可以重现的maven工程
public class FastJson2Reader {
public static class JsonReaderModule implements ObjectReaderModule {
@Override
public ObjectReader getObjectReader(Type type) {
if (type instanceof ParameterizedType) {
var ptype = (ParameterizedType) type;
if (ptype.getRawType() == MyArrayList.class) {
return ObjectReaderImplList.of(type, null, 0);
}
}
return ObjectReaderModule.super.getObjectReader(type);
}
}
public static void init() {
JSON.register(new JsonReaderModule());
}
}
public class Main {
public static class Player {
public int level;
public int exp;
public Player() {
}
public Player(int level, int exp) {
this.level = level;
this.exp = exp;
}
}
public static class Game {
private MyArrayList<Player> players = new MyArrayList<>();
public MyArrayList<Player> getPlayers() {
return players;
}
public void setPlayers(MyArrayList<Player> players) {
this.players = players;
}
}
public static <T> T parseJSONObject(String json, Class<T> clazz) {
var jsonObj = JSON.parse(json);
if (jsonObj instanceof JSONObject) {
return ((JSONObject) jsonObj).to(clazz);
} else if (jsonObj instanceof JSONArray) {
return ((JSONArray) jsonObj).to(clazz);
}
throw new RuntimeException("unexpected instance!");
}
public static void main(String[] args) {
FastJson2Reader.init();
var game = new Game();
game.players.addAll(List.of(new Player(1, 100), new Player(2, 200)));
var gameJson = JSON.toJSONString(game);
var deserializedGame1 = JSON.parseObject(gameJson, Game.class);
var deserializedGame2 = parseJSONObject(gameJson, Game.class);
System.out.println("deserializedList1.0 is Player=" + (deserializedGame1.players.get(0).getClass() == Player.class));
System.out.println("deserializedGame2.0 is Player=" + (deserializedGame2.players.get(0).getClass() == Player.class));
}
}
期待的正确结果
我希望自定义ObjectReader的泛型List类,作为字段时,仍然可以政策反序列化
相关日志输出
请复制并粘贴任何相关的日志输出。
附加信息
如果你还有其他需要提供的信息,可以在这里填写(可以提供截图、视频等)。