Skip to content

Conversation

@jujn
Copy link
Contributor

@jujn jujn commented Dec 11, 2025

….to, for issue #3901

对没有实现 createInstance 方法的类型使用 JSON.parseObject(this.toJSONString(), clazz, features),但这里会增加一次序列化的开销,目前没有想到更好的修复方案

Copilot AI review requested due to automatic review settings December 11, 2025 13:29
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 UnsupportedOperationException in JSONObject.to(Class<T>, JSONReader.Feature...)
  • Fallback uses JSON.parseObject(this.toJSONString(), clazz, features) when createInstance is unsupported
  • Added test case to verify the fix works with a custom ObjectReader that only implements readObject

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.

@jfinal
Copy link

jfinal commented Dec 11, 2025

这里的问题在于即便正确实现 createInstance 方法,仍然会出现另一个新的异常。 在 catch 中通过 JSON.parseObject(this.toJSONString(), clazz, features) 的方式一是抛出异常有性能损耗,二是多一次 toJSONString() 转换有性能损耗。

更希望是在实现 createInstance 方法的基础之上,能解决那另一个异常,这样起码性能上有保障。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants