fix: Handle custom ObjectReaders lacking createInstance in JSONObject…#3902
fix: Handle custom ObjectReaders lacking createInstance in JSONObject…#3902jujn wants to merge 3 commits intoalibaba:mainfrom
Conversation
There was a problem hiding this comment.
Pull request overview
This PR fixes issue #3901 by adding fallback handling for custom ObjectReader implementations that don't implement the createInstance method. When a custom reader throws UnsupportedOperationException during object instantiation, the code now falls back to serializing the JSONObject to a JSON string and re-parsing it, which invokes the custom reader's readObject method instead.
Key Changes:
- Added try-catch block to handle
UnsupportedOperationExceptioninJSONObject.to(Class<T>, JSONReader.Feature...) - Fallback uses
JSON.parseObject(this.toJSONString(), clazz, features)whencreateInstanceis unsupported - Added test case to verify the fix works with a custom
ObjectReaderthat only implementsreadObject
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| core/src/main/java/com/alibaba/fastjson2/JSONObject.java | Added exception handling in the to() method to catch UnsupportedOperationException from createInstance() and fall back to JSON string parsing |
| core/src/test/java/com/alibaba/fastjson2/issues_3900/Issue3901.java | Added test case demonstrating a custom ObjectReader that only implements readObject and verifies the fallback mechanism works correctly |
Comments suppressed due to low confidence (1)
core/src/test/java/com/alibaba/fastjson2/issues_3900/Issue3901.java:34
- UserReader should be made static, since the enclosing instance is not used.
public class UserReader implements ObjectReader {
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
core/src/test/java/com/alibaba/fastjson2/issues_3900/Issue3901.java
Outdated
Show resolved
Hide resolved
|
这里的问题在于即便正确实现 createInstance 方法,仍然会出现另一个新的异常。 在 catch 中通过 JSON.parseObject(this.toJSONString(), clazz, features) 的方式一是抛出异常有性能损耗,二是多一次 toJSONString() 转换有性能损耗。 更希望是在实现 createInstance 方法的基础之上,能解决那另一个异常,这样起码性能上有保障。 |
|
@wenshao ,简单总结该问题就是,用户注册自定义反序列化器,仅实现了 readObject ,但是如果调用 JSONObject/JSONArray 相关 api 时,会调用 ObjectReader 默认的 createInstance (map、collection 版本)直接抛异常。我发现框架没有办法预判用户期望的反序列化行为,所以为保持高性能貌似只能让用户自定义 createInstance 。直接在文档里注明可以吗?(可以参考我新提交的代码示例) |
….to, for issue #3901
对没有实现 createInstance 方法的类型使用 JSON.parseObject(this.toJSONString(), clazz, features),但这里会增加一次序列化的开销,目前没有想到更好的修复方案