Skip to content

[BUG]通过ObjectReader定制反序列化后,其所对应的类型无法再使用JSONObject.to(...) 与 JSONObject.getObject(...) 方法 #3901

@jfinal

Description

@jfinal

问题描述

通过 ObjectReader 定制反序列化后,其所对应的类型无法再使用JSONObject.to(...) 与 JSONObject.getObject(...) 方法,必定抛出异常

环境信息

请填写以下信息:

  • OS信息: [Mac OS 15.3.2]
  • JDK信息: [jdk 1.8.0_312]
  • 版本信息:[Fastjson2 2.0.60]

重现步骤

运行如下代码重现:

public class UserReader implements ObjectReader<Object> {
    public Object readObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) {
        // 这里返回 user 仅为示例,JSONObject.to(...) 不会走到这里
        return new User();
    }
}

public class User {
    String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

public class FastJsonTest {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "James");

        // 未注册 UserReader 之前功能正常
        User user = jsonObject.to(User.class);

        // 注册 UserReader
        JSON.register(User.class, new UserReader());

        // 注册后得先转成 String 才能使用 JSONObject.to(...)、JSONObject.getObject()
        user = JSON.parseObject(jsonObject.toJSONString(), User.class);

        // 注册后 JSONObject.to(...)、JSONObject.getObject() 都将无法使用
        user = jsonObject.to(User.class);

        System.out.println(user.getName());
    }
}

代码说明

只要 JSON.register(User.class, new UserReader()) 注册了 ObjectReader 定制反序列化实现,JSONObject.to(...) 与JSONObject.getObject() 就一定用不了。

但通过 JSONObject.toJSONString() 将先数据转成 json string,再通过 JSON.parseObject(...) 转换为 bean 是可以实现的。

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions