Skip to content

fix(core): validate cached field writer by value type in toJSONObject - #7739

Merged
wenshao merged 3 commits into
alibaba:mainfrom
fudianchn:fix/tojsonobject-cached-writer-typematch-7714
Sep 7, 2026
Merged

wenshao merged 3 commits into
alibaba:mainfrom
fudianchn:fix/tojsonobject-cached-writer-typematch-7714

Conversation

@fudianchn

@fudianchn fudianchn commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

AI disclosure: this change was prepared with AI coding agents, reviewed and revised line by line by me.

What

ObjectWriterAdapter.toJSONObject(T, long) now checks whether the field writer cached for an Object / generic field still matches the current value's runtime type before reusing it, instead of throwing JSONException: key get error (a wrapped ClassCastException).

Why

For a bean with an Object (or generic) field, FieldWriterObject caches the ObjectWriter of the first value it serializes (initValueClass / initObjectWriter). The write path (FieldWriterObject.getObjectWriter(jsonWriter, valueClass)) validates this cache via typeMatch and re-resolves on mismatch. The toJSONObject path did not — it pulled the cached writer via getInitWriter() and used it unconditionally, so when a later value had a different runtime type the writer's field accessors threw ClassCastException, wrapped as JSONException: key get error.

This commonly hits MQ-style envelopes with an untyped payload field (public <T> T getPayload()): after one JSON.toJSONString(msg) with a typed payload, a later JSON.toJSON(msg) with a String payload on the same bean class blows up.

Root cause

ObjectWriterAdapter.java:684 resolved the field value writer via fieldWriter.getInitWriter() (the cached writer) with no validation that its initValueClass still matches fieldValue.getClass().

How

  • Extract the write path's exact-class typeMatch predicate into FieldWriterObject.isTypeMatch(Class) and call it from both ObjectWriterAdapter.toJSONObject and FieldWriterObject.getObjectWriter, so the two paths share one predicate and cannot drift. A subclass value no longer matches the parent's cached writer (matching toJSONString), so its fields are no longer silently dropped.
  • Right after resolving the cached writer, compare initValueClass to the actual value. On mismatch, re-resolve the writer via JSONFactory.getObjectWriter(fieldValue.getClass(), features) — mirroring the typeMatch re-resolution the write path already performs. When the re-resolved writer is not an ObjectWriterAdapter (arrays, Date, enums, etc.), convert the value via JSON.toJSON so its in-memory shape matches the unprimed path and toJSONString.
  • When initValueClass is null (nothing cached yet) or matches, behavior is unchanged.

Testing

New test Issue7714 (4 cases). 3 fail before the fix (two with the issue's JSONException: key get error, one with silent subclass-field loss), all pass after; the 4th guards the unchanged match path:

  • toJSON_afterWriterCachedForDifferentType — the issue's scenario: cache a DataChangeNotification writer via toJSONString, then JSON.toJSON a String payload. Before: JSONException: key get error (ClassCastException: String cannot be cast to DataChangeNotification). After: the String payload is preserved.
  • toJSON_beanToBeanSubclassReparseAndRecurses — cache the writer for the parent type, then JSON.toJSON a subclass payload (DataChangeNotificationExt, adds scope). Before: expected: <online> but was: <null> (the subclass field was dropped by the parent's cached writer). After: payload is a nested JSONObject carrying scope, and toJSON agrees with toJSONString.
  • toJSON_nonAdapterValueAfterBeanCacheConvertsLikeUnprimed — prime the field with a bean, then send an int[] payload whose re-resolved writer is not an ObjectWriterAdapter. Before: JSONException: key get error (ClassCastException: [I cannot be cast to DataChangeNotification). After: payload is a JSONArray, matching the unprimed path.
  • toJSON_consistentAfterWriterCachedForSameType — regression guard: a second value of the cached type still converts to a nested JSONObject (passes before and after, guarding the unchanged match path).
  • ./mvnw checkstyle:check → 0 Checkstyle violations.
  • Regression: JSONTest, JSONObjectTest, JSONReader*Test, *ObjectWriter*Test, Issue* → Tests run: 2501, Failures: 0.

Verification of the original issue

Before the fix:

JSON.toJSON(m2) → JSONException: key get error
  Caused by: ClassCastException: class java.lang.String cannot be cast to class ...DataChangeNotification

After the fix:

JSON.toJSON(m2) → {"payload":"{\"key\":\"abc\"}"}

The String payload is preserved as-is instead of being fed to the wrong writer.

Fixes #7714

@wenshao wenshao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed. Suggestions are inline.

— qwen3.8-max-preview via Qwen Code /review (v0.21.3)

// check FieldWriterObject.getObjectWriter(jsonWriter, valueClass) does on the write
// path. See issue #7714.
Class initValueClass = ((FieldWriterObject) fieldWriter).initValueClass;
if (valueWriter != null && initValueClass != null && !initValueClass.isInstance(fieldValue)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[Suggestion] The isInstance predicate diverges from the write path's typeMatch check in FieldWriterObject.getObjectWriter: isInstance accepts any subclass, while the write path requires exact class identity (plus narrow writeUsing/Map/List exceptions). For subclass values, toJSONObject reuses the superclass's cached writer (silently dropping subclass-specific fields) while toJSONString re-resolves and includes them — the two APIs produce different JSON for the same object. The comment above claims to mirror typeMatch but the predicate does not match. — Concrete cost: a bean with an Object field first serialized as Base, then as Sub extends Base — toJSONString includes Sub's extra fields, toJSON drops them. A maintainer debugging this divergence reads the "mirroring typeMatch" comment and looks elsewhere.

Suggested change
if (valueWriter != null && initValueClass != null && !initValueClass.isInstance(fieldValue)) {
Class initValueClass = ((FieldWriterObject) fieldWriter).initValueClass;
if (valueWriter != null && initValueClass != null && initValueClass != fieldValue.getClass()) {
valueWriter = JSONFactory.getObjectWriter(fieldValue.getClass(), this.features | features);

— qwen3.8-max-preview via Qwen Code /review (v0.21.3)

@fudianchn fudianchn Aug 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

isInstance is strictly looser than the write path's typeMatch, so a subclass value would still reuse the parent's cached writer and silently drop the subclass fields, making toJSON diverge from toJSONString.

Fixed by extracting the write path's predicate into FieldWriterObject.isTypeMatch(Class valueClass) (exact class identity plus the same writeUsing / Map / List / primitive-boxing exceptions) and calling it from ObjectWriterAdapter.toJSONObject. Both paths now share one strict predicate, so a subclass value triggers re-resolution by its actual class, consistent with toJSONString.

I also pointed getObjectWriter itself at the new helper so the two cannot drift again.

Sanity check: with the old isInstance logic the new subclass test fails with expected: <online> but was: <null> (subclass field dropped); with isTypeMatch it passes.

Comment on lines +63 to +65
DefaultMessage m2 = new DefaultMessage();
m2.setPayload("{\"key\":\"abc\"}");
Object r = JSON.toJSON(m2);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[Suggestion] Neither test exercises the fix's re-resolution-then-convert branch with a bean-to-bean type switch. Test 1 uses a String payload (re-resolved writer is not an ObjectWriterAdapter, so the recursive toJSONObject call is not taken). Test 2 uses the same type (no re-resolution). A future regression that discards conversion on mismatch (e.g. simplifying to valueWriter = null) would pass both tests, yet JSON.toJSON would return a raw bean instead of a nested JSONObject. — Concrete cost: the branch the fix actually added (re-resolve → ObjectWriterAdapter.toJSONObject(fieldValue)) has no regression guard.

Suggested fix: add a third test that primes the cache via toJSONString with DataChangeNotification, then calls toJSON with a different bean type payload, and asserts the result is a nested JSONObject carrying the second bean's fields.

— qwen3.8-max-preview via Qwen Code /review (v0.21.3)

@fudianchn fudianchn Aug 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The original tests left that branch uncovered (Test1's String payload never reaches the recursive toJSONObject; Test2 never re-resolves). A future regression that simplifies this back to valueWriter = null would pass both while toJSON returns the raw bean instead of a nested JSONObject.

Added toJSON_beanToBeanSubclassReparseAndRecurses: it caches the writer for the parent type (DataChangeNotification) via toJSONString, then calls toJSON with a subclass payload (DataChangeNotificationExt, which adds a scope field). It asserts:

  • the payload is a nested JSONObject (not the raw bean, assertNotSame),
  • the subclass field scope is preserved,
  • toJSON and toJSONString produce identical output for the same object.

This exercises the re-resolve-then-recurse path and directly encodes the toJSON/toJSONString consistency guarantee. Verified it fails on the previous isInstance logic (expected: <online> but was: <null>).

For Object/generic fields, FieldWriterObject caches the writer of the first
serialized value. toJSONObject reused it unconditionally, so a later value of a
different runtime type raised JSONException 'key get error' (wrapped
ClassCastException); and for a subclass value it reused the parent writer and
silently dropped the subclass fields, diverging from toJSONString.

Re-resolve the writer by the actual value class using the same typeMatch check
the write path applies in FieldWriterObject.getObjectWriter. Extract that check
into FieldWriterObject.isTypeMatch so both paths share one strict predicate
(exact class match plus the writeUsing / Map / List / primitive-boxing
exceptions), keeping toJSON consistent with toJSONString.

Addresses review: aligns toJSONObject with the write path's exact-class
typeMatch rather than the looser isInstance check, and adds a bean->bean subclass
regression test covering the re-parse + recursive toJSONObject branch.

See issue alibaba#7714.
@fudianchn
fudianchn force-pushed the fix/tojsonobject-cached-writer-typematch-7714 branch from a4c8249 to 6c29d27 Compare August 2, 2026 03:31
@fudianchn

Copy link
Copy Markdown
Contributor Author

Pushed an update addressing both suggestions.

R1-1 (typeMatch divergence): Replaced the looser isInstance check with the write path's exact-class typeMatch predicate. Extracted it into FieldWriterObject.isTypeMatch(Class) and called it from both ObjectWriterAdapter.toJSONObject and FieldWriterObject.getObjectWriter, so the two paths share one predicate and cannot drift. A subclass value now re-resolves the writer by its actual class, matching toJSONString.

R1-2 (missing test branch): Added toJSON_beanToBeanSubclassReparseAndRecurses covering the bean->bean-subclass re-resolve + recursive toJSONObject branch, asserting the subclass field is preserved, the payload is a nested JSONObject (not the raw bean), and toJSON agrees with toJSONString.

Verification (commit 6c29d27):

  • Issue7714: 3/3 pass (incl. the new test). The new test fails on the prior isInstance logic with expected: <online> but was: <null>, confirming it guards the fix.
  • Regression: JSONTest, JSONObjectTest, JSONReader*Test, *ObjectWriter*Test, Issue* → 2500/2500 pass.
  • checkstyle:check (fastjson2-checks.xml): 0 violations.

@wenshao wenshao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed. Suggestions are inline.

— qwen3.8-max-preview via Qwen Code /review (v0.21.3)

* {@code JSONException: key get error} (a wrapped ClassCastException), and — for a subclass
* value — silently dropping the subclass fields by reusing the parent writer.
*/
public class Issue7714 {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[Suggestion] Missing @Tag("regression") annotation that 270 of 273 sibling Issue*.java files in this directory carry. — Concrete cost: when the test suite is filtered by the regression tag (e.g. mvn test -Dgroups=regression), this regression test for issue #7714 is silently excluded, so a future regression in the toJSONObject type-match fix would not be caught by tagged regression runs.

Suggested change
public class Issue7714 {
@Tag("regression")
public class Issue7714 {

— qwen3.8-max-preview via Qwen Code /review (v0.21.3)

@fudianchn fudianchn Aug 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done: added @Tag("regression") to Issue7714 (commit ff1a7e9) so it is picked up by mvn test -Dgroups=regression, matching the sibling Issue*.java files.

Verified: Issue7714 3/3 pass, 0 Checkstyle violations.

Add @tag("regression") so the test is included in tagged regression runs
(mvn test -Dgroups=regression), matching the convention used by the other
270/273 sibling Issue*.java files in this directory.

@wenshao wenshao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed — no blockers. Suggestions are inline.

— qwen3.8-max-preview via Qwen Code /review (v0.21.3)

Comment on lines +697 to +699
if (objectFieldWriter.initValueClass != null
&& !objectFieldWriter.isTypeMatch(fieldValue.getClass())) {
valueWriter = JSONFactory.getObjectWriter(fieldValue.getClass(), this.features | features);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[Suggestion] When the re-resolved writer here is not an ObjectWriterAdapter (arrays, Date, enums, etc.), the raw Java object is put into the result JSONObject, while the unprimed path converts the same value via JSON.toJSON — so the in-memory graph shape of JSON.toJSON depends on whether a bean payload was previously serialized on the same field in this JVM. — Concrete cost: probe-verified — with an Object payload field, a fresh JVM stores an int[] payload as JSONArray and a Date payload as String; after toJSONString primes the field with a bean payload, the identical inputs store a raw int[] / java.util.Date. (JSONArray) ((JSONObject) JSON.toJSON(msg)).get("payload") passes in unit tests but throws ClassCastException in a long-lived process (cache-order heisenbug). Pre-PR the primed case threw, so this is not a regression — but it undercuts the consistency the added comment claims.

Suggested change
if (objectFieldWriter.initValueClass != null
&& !objectFieldWriter.isTypeMatch(fieldValue.getClass())) {
valueWriter = JSONFactory.getObjectWriter(fieldValue.getClass(), this.features | features);
if (objectFieldWriter.initValueClass != null
&& !objectFieldWriter.isTypeMatch(fieldValue.getClass())) {
valueWriter = JSONFactory.getObjectWriter(fieldValue.getClass(), this.features | features);
if (!(valueWriter instanceof ObjectWriterAdapter)) {
fieldValue = JSON.toJSON(fieldValue);
}

— qwen3.8-max-preview via Qwen Code /review (v0.21.3)

@fudianchn fudianchn Aug 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 514f3af: when the re-resolved writer is not an ObjectWriterAdapter (arrays, Date, enums, ...), the value is now converted via JSON.toJSON(fieldValue) so the stored shape matches the unprimed path and toJSONString, mirroring the existing JSON.toJSON fallback just below. Added toJSON_nonAdapterValueAfterBeanCacheConvertsLikeUnprimed (primed bean field, then int[] payload -> asserts JSONArray), which fails before the conversion.

The broader primed+match case (e.g. an Object field first primed with a bean, later a Date) shares the same raw-object trait and predates this PR; left out of scope as it changes behavior outside issue #7714.

Comment on lines +106 to +108
public boolean isTypeMatch(Class valueClass) {
final Class initValueClass = this.initValueClass;
boolean typeMatch = initValueClass == valueClass

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[Suggestion] isTypeMatch NPEs when initValueClass is null — the precondition is undocumented and both current callers guard externally. — Concrete cost: initValueClass is null for every FieldWriterObject until the first value is serialized through it; a future caller of this public method (its javadoc invites reuse) that omits the external null guard hits NullPointerException at initValueClass.isPrimitive() / isAssignableFrom(...). The write path's guard (getObjectWriter returns getObjectWriterVoid when initValueClass == null) was not carried into the extracted method.

Suggested change
public boolean isTypeMatch(Class valueClass) {
final Class initValueClass = this.initValueClass;
boolean typeMatch = initValueClass == valueClass
public boolean isTypeMatch(Class valueClass) {
final Class initValueClass = this.initValueClass;
if (initValueClass == null) {
return false;
}
boolean typeMatch = initValueClass == valueClass

— qwen3.8-max-preview via Qwen Code /review (v0.21.3)

@fudianchn fudianchn Aug 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 514f3af: isTypeMatch now returns false when initValueClass == null (matching the write path's getObjectWriter guard that returns getObjectWriterVoid in that case), with a javadoc note on the precondition. Both current callers already guard externally, so this is defensive and self-documenting for future callers of the public method.

…oJSONObject

Address review follow-ups on issue alibaba#7714:

- FieldWriterObject.isTypeMatch now returns false when initValueClass is
  null (no value observed yet), matching the write path's guard and making
  the public method safe for callers that do not pre-check, with a javadoc
  note on the precondition.

- ObjectWriterAdapter.toJSONObject: when a re-resolved value writer is not
  an ObjectWriterAdapter (arrays, Date, enums, ...), convert the value via
  JSON.toJSON so the stored shape matches the unprimed path and toJSONString,
  rather than leaving the raw Java object in the JSONObject. Mirrors the
  existing JSON.toJSON fallback below.

Added a regression test (primed bean field, then int[] payload) that fails
before the conversion and passes now.

Signed-off-by: 付典 <[email protected]>
@wenshao
wenshao merged commit 07abc2f into alibaba:main Sep 7, 2026
29 checks passed

@wenshao wenshao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed. Suggestions are inline.

Not explored to full depth (tool budget reached): "agent 6b": did not run the repo's Maven suite in the shared worktree (builds in place are barred); relied on code-path verification and the merged PR's CI for the priming ….

Deferred under the convergence posture (round 4, not a blocker) — recorded, not requested in this round:

  • core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterAdapter.java:643 — [review] Unwrapped branch still lacks the typeMatch guard (deferred: age rule)
  • core/src/main/java/com/alibaba/fastjson2/writer/FieldWriterObject.java:114 — [review] writeUsing branch of isTypeMatch untested from new consumer (deferred: age rule)

Convergence: round 4 posted 2 inline comment(s), 2 of them reported for the first time. Findings keep coming back to the same files: core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterAdapter.java (findings in round 3; 1 more now). A cluster that keeps producing siblings usually means the fixes are treating instances of a shared root cause — triaging that cause before the next round, or splitting an independent cluster into its own pull request, tends to end the loop faster than fixing them one at a time. (Observation only — nothing was withheld from this review because of this observation.)

— glm-5.3-flash via Qwen Code /review (v0.23.0)

Comment on lines +704 to +706
if (!(valueWriter instanceof ObjectWriterAdapter)) {
fieldValue = JSON.toJSON(fieldValue);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[Suggestion] R3-1: (fix-induced) The new mismatch conversion leg (fieldValue = JSON.toJSON(fieldValue)) renders the value through a default write context, discarding both the field's @JSONField(format …) and the caller's JSONWriter features — so JSON.toJSON still diverges from JSON.toJSONString on this newly-reachable mismatch path, the consistency the comment above promises. The round-3 fix closed the raw-put defect; the conversion leg it added re-opens the divergence class at this site. Concretely: prime an Object-typed payload field with a bean via toJSONString, then send a non-bean payload — with format="yyyy-MM-dd" and a ZonedDateTime payload, toJSONString emits "2026-09-07" while toJSON stores "2026-09-07T15:04:05[Asia/Shanghai]"; with BrowserCompatible and a long[]{5, 9007199254740993} payload, toJSONString writes "9007199254740993" as a string while toJSON stores raw numbers [5,9007199254740993]. Before this fix both inputs threw the wrapped ClassCastException, so the silent divergence is new surface of this change. (java.util.Date does not diverge — FieldWriter.getObjectWriter has no java.util.Date branch, so the write path ignores the format there too.)

Witness:

[F1:ZonedDateTime] toJSONString.payload=2026-09-07 | toJSON.payload=2026-09-07T15:04:05[Asia/Shanghai] MATCH=false
[F7:BrowserCompatible] toJSON.tree={"payload":[5,9007199254740993]} vs toJSONString={"payload":[5,"9007199254740993"]} MATCH=false
flip checks (format-aware resolution + render via the resolved writer; context carrying this.features | features): MATCH=true, Issue7714 4/4 green
PR hunk reverted: BASE: JSONException: k get error vs PR: {"payload":[5,9007199254740993]}

Suggested fix — one coherent change in this block: resolve format-aware first (FieldWriter.getObjectWriter(fieldType, fieldClass, format, null, valueClass) when format != null, mirroring getObjectWriterTypeNotMatch), then render through the resolved writer with a context carrying this.features | features (mirror JSON.toJSON's own fallback, JSON.java:4092-4097) instead of the one-arg JSON.toJSON; keep the adapter-recurse vs convert decision on the resolved writer, and share that conversion with the unprimed empty-adapter leg below so primed and unprimed outputs stay identical. Fixing only the resolution is verified not to flip the probe — this conversion leg never dereferences valueWriter.

The fix must not change default-context output (the four existing tests pin int[] → numeric JSONArray) and must not touch the write path's own mismatch leg (FieldWriterObject.getObjectWriterTypeNotMatch). Please add the pinning tests to this class — a formatted-temporal variant and a BrowserCompatible variant asserting ((JSONObject) r).toJSONString() equals JSON.toJSONString(m2, …) — and confirm they go red if either half of the fix is removed.

— glm-5.3-flash via Qwen Code /review (v0.23.0)

Comment on lines +156 to +157
// JSONArray — matching the unprimed path and toJSONString — rather than stored as a raw
// int[] whose shape depends on cache priming order.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[Suggestion] The unprimed baseline this conversion claims parity with ("matching the shape the unprimed path and toJSONString produce") is asserted by no test: all four tests in this class prime the cache before asserting, and no test in core/src/test pins the unprimed Object-field shapes. A future refactor of the unprimed branch back to storing raw values would keep this suite green while reintroducing the cache-order-dependent trees this fix exists to kill — primed payloads converted, unprimed ones raw.

Witness:

[F3:bean] payload={"u":"uu"} class=com.alibaba.fastjson2.JSONObject
[F3:int[]] payload=[7,8] class=com.alibaba.fastjson2.JSONArray   (fresh never-primed fixture classes)

Suggested fix: add one test using bean classes no other test uses (the global writer cache's priming persists for the JVM lifetime, so reused classes would make the assertion suite-order-dependent): unprimed bean payload → JSONObject with the bean's fields, unprimed int[] payload → JSONArray. It must go red if the unprimed empty-adapter conversion in toJSONObject stops converting — leave the raw value and this test fails while the primed ones stay green; please verify that mutation before merging.

— glm-5.3-flash via Qwen Code /review (v0.23.0)

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.

[BUG]Payload为Object或泛型时可能会抛JSONException: key get error

2 participants