Repository navigation
Conversation
wenshao
left a comment
There was a problem hiding this comment.
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)) { |
There was a problem hiding this comment.
[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.
| 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)
There was a problem hiding this comment.
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.
| DefaultMessage m2 = new DefaultMessage(); | ||
| m2.setPayload("{\"key\":\"abc\"}"); | ||
| Object r = JSON.toJSON(m2); |
There was a problem hiding this comment.
[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)
There was a problem hiding this comment.
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
scopeis preserved, toJSONandtoJSONStringproduce 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.
a4c8249 to
6c29d27
Compare
|
Pushed an update addressing both suggestions. R1-1 (typeMatch divergence): Replaced the looser R1-2 (missing test branch): Added Verification (commit 6c29d27):
|
wenshao
left a comment
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
[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.
| public class Issue7714 { | |
| @Tag("regression") | |
| public class Issue7714 { |
— qwen3.8-max-preview via Qwen Code /review (v0.21.3)
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Reviewed — no blockers. Suggestions are inline.
— qwen3.8-max-preview via Qwen Code /review (v0.21.3)
| if (objectFieldWriter.initValueClass != null | ||
| && !objectFieldWriter.isTypeMatch(fieldValue.getClass())) { | ||
| valueWriter = JSONFactory.getObjectWriter(fieldValue.getClass(), this.features | features); |
There was a problem hiding this comment.
[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.
| 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)
There was a problem hiding this comment.
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.
| public boolean isTypeMatch(Class valueClass) { | ||
| final Class initValueClass = this.initValueClass; | ||
| boolean typeMatch = initValueClass == valueClass |
There was a problem hiding this comment.
[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.
| 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)
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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)
| if (!(valueWriter instanceof ObjectWriterAdapter)) { | ||
| fieldValue = JSON.toJSON(fieldValue); | ||
| } |
There was a problem hiding this comment.
[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)
| // JSONArray — matching the unprimed path and toJSONString — rather than stored as a raw | ||
| // int[] whose shape depends on cache priming order. |
There was a problem hiding this comment.
[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)
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 anObject/ generic field still matches the current value's runtime type before reusing it, instead of throwingJSONException: key get error(a wrappedClassCastException).Why
For a bean with an
Object(or generic) field,FieldWriterObjectcaches theObjectWriterof the first value it serializes (initValueClass/initObjectWriter). The write path (FieldWriterObject.getObjectWriter(jsonWriter, valueClass)) validates this cache viatypeMatchand re-resolves on mismatch. ThetoJSONObjectpath did not — it pulled the cached writer viagetInitWriter()and used it unconditionally, so when a later value had a different runtime type the writer's field accessors threwClassCastException, wrapped asJSONException: key get error.This commonly hits MQ-style envelopes with an untyped
payloadfield (public <T> T getPayload()): after oneJSON.toJSONString(msg)with a typed payload, a laterJSON.toJSON(msg)with aStringpayload on the same bean class blows up.Root cause
ObjectWriterAdapter.java:684resolved the field value writer viafieldWriter.getInitWriter()(the cached writer) with no validation that itsinitValueClassstill matchesfieldValue.getClass().How
typeMatchpredicate intoFieldWriterObject.isTypeMatch(Class)and call it from bothObjectWriterAdapter.toJSONObjectandFieldWriterObject.getObjectWriter, so the two paths share one predicate and cannot drift. A subclass value no longer matches the parent's cached writer (matchingtoJSONString), so its fields are no longer silently dropped.initValueClassto the actual value. On mismatch, re-resolve the writer viaJSONFactory.getObjectWriter(fieldValue.getClass(), features)— mirroring thetypeMatchre-resolution the write path already performs. When the re-resolved writer is not anObjectWriterAdapter(arrays,Date, enums, etc.), convert the value viaJSON.toJSONso its in-memory shape matches the unprimed path andtoJSONString.initValueClassisnull(nothing cached yet) or matches, behavior is unchanged.Testing
New test
Issue7714(4 cases). 3 fail before the fix (two with the issue'sJSONException: 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 aDataChangeNotificationwriter viatoJSONString, thenJSON.toJSONaStringpayload. Before:JSONException: key get error(ClassCastException: String cannot be cast to DataChangeNotification). After: theStringpayload is preserved.toJSON_beanToBeanSubclassReparseAndRecurses— cache the writer for the parent type, thenJSON.toJSONa subclass payload (DataChangeNotificationExt, addsscope). Before:expected: <online> but was: <null>(the subclass field was dropped by the parent's cached writer). After: payload is a nestedJSONObjectcarryingscope, andtoJSONagrees withtoJSONString.toJSON_nonAdapterValueAfterBeanCacheConvertsLikeUnprimed— prime the field with a bean, then send anint[]payload whose re-resolved writer is not anObjectWriterAdapter. Before:JSONException: key get error(ClassCastException: [I cannot be cast to DataChangeNotification). After: payload is aJSONArray, matching the unprimed path.toJSON_consistentAfterWriterCachedForSameType— regression guard: a second value of the cached type still converts to a nestedJSONObject(passes before and after, guarding the unchanged match path)../mvnw checkstyle:check→0 Checkstyle violations.JSONTest, JSONObjectTest, JSONReader*Test, *ObjectWriter*Test, Issue*→Tests run: 2501, Failures: 0.Verification of the original issue
Before the fix:
After the fix:
The
Stringpayload is preserved as-is instead of being fed to the wrong writer.Fixes #7714