Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[QUESTION] fastjson2和fastjson抽象类反序列化默认行为不一致 #3143

Open
rock-byte opened this issue Oct 31, 2024 · 1 comment
Open
Labels
question Further information is requested

Comments

@rock-byte
Copy link

问题描述

fastjson2和fastjson抽象类反序列化默认行为不一致,fastjson2在反序列化抽象类时会抛出异常,fastjson会跳过该类。并没有找到配置项控制该行为。

重现步骤

public static abstract class Foo {

        private String value;
    }

    public static void main(String[] args) {
        String jsonString = "{\"value\":\"bar\"}";
        com.alibaba.fastjson2.JSON.config(JSONReader.Feature.FieldBased);
        Foo fooBefore = com.alibaba.fastjson.JSON.parseObject(jsonString, Foo.class);
        System.out.println(fooBefore);
        Foo foo = com.alibaba.fastjson2.JSON.parseObject(jsonString, Foo.class);
        System.out.println(foo);
    }

结果

null
Exception in thread "main" com.alibaba.fastjson2.JSONException: create instance error, class Test$Foo
	at com.alibaba.fastjson2.reader.ObjectReaderAdapter.createInstance(ObjectReaderAdapter.java:411)
	at com.alibaba.fastjson2.reader.ObjectReaderBean.readObject(ObjectReaderBean.java:386)
	at com.alibaba.fastjson2.JSON.parseObject(JSON.java:864)
	at Test.main(Test.java:19)
Caused by: java.lang.InstantiationException
	at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at com.alibaba.fastjson2.reader.ObjectReaderAdapter.createInstance(ObjectReaderAdapter.java:405)
	... 3 more

期待结果

fastjson2和fastjson对于抽象类反序列化默认行为一致,或至少提供配置项控制。

@rock-byte rock-byte added the question Further information is requested label Oct 31, 2024
@rock-byte rock-byte changed the title [QUESTION] fastjson2和fastjson抽象类反序列化默认行为不一致 [BUG] fastjson2和fastjson抽象类反序列化默认行为不一致 Oct 31, 2024
@rock-byte rock-byte changed the title [BUG] fastjson2和fastjson抽象类反序列化默认行为不一致 [QUESTION] fastjson2和fastjson抽象类反序列化默认行为不一致 Oct 31, 2024
@rock-byte rock-byte reopened this Nov 5, 2024
@amabilee
Copy link

amabilee commented Nov 5, 2024

Have you tried instead of directly deserializing the abstract class, deserialize a concrete subclass that extends the abstract class?
This way, you can avoid the exception thrown by fastjson2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants