Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions core/src/main/java/com/alibaba/fastjson2/writer/FieldWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ public void writeEnum(JSONWriter jsonWriter, Enum e) {

public void writeBinary(JSONWriter jsonWriter, byte[] value) {
if (value == null) {
if (!jsonWriter.isWriteNulls()) {
if ((jsonWriter.getFeatures(this.features) & WriteNulls.mask) == 0) {

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] R1-3: the fix never executes on the filtered write path — ObjectWriterAdapter.write's filtered loop pre-skips nulls with the context-only isWriteNulls() before any per-field writer runs.

Line 602 (if (fieldValue == null && !jsonWriter.isWriteNulls()) continue;) drops annotated null fields whenever ANY NameFilter/PropertyFilter/ValueFilter is attached, while the no-filter fast path (582-589 → fieldWriter.write) honors them — adding an unrelated filter silently changes null-handling output. (Pre-existing for the fields that already worked; this diff extends the fast-path feature — and therefore this inconsistency — to int[]/long[]/enum.)

Witness (probe on PR head, reflect creator; the only difference is a no-op NameFilter):

E-F3 plain    : {"bin":null,"dateField":null,"enumField":null,"longArr":null,"strField":null}
E-F3 filtered : {}

Suggested fix: merge field features into the pre-skip — if (fieldValue == null && (jsonWriter.getFeatures(fieldWriter.features) & WriteNulls.mask) == 0) continue; — and decide/document whether null values become visible to filters. The filter chain (propertyPreFilter/nameFilter/contextNameFilter, 568-599) must keep its interposition semantics; the context-only isWriteNulls() at ObjectWriterImplMap.java:151 is non-field context and stays unchanged.

Acceptance criterion: an Issue7773 test serializing ForcedNulls with a pass-through PropertyFilter asserting all NULL_FIELDS still appear — RED while line 602 is context-only; please remove the merge and confirm it reds.

中文说明

修复在「带过滤器」的写出路径上不会生效:ObjectWriterAdapter.write 的过滤循环在到达任何字段写出器之前,就用只看 context 的 isWriteNulls()(602 行)把 null 字段预跳过了。只要挂了任意 NameFilter/PropertyFilter/ValueFilter,字段级 WriteNulls 就被忽略;而无过滤器的快速路径(582-589 → fieldWriter.write)能正确生效——加一个无关过滤器会静默改变 null 处理输出(实测:plain 全部写出,filtered {})。注:对修复前就已生效的两个字段这是既有问题,本 PR 把快速路径特性扩展到 int[]/long[]/enum 后,该不一致也随之扩大。

建议:把字段特性并入预跳过判断(jsonWriter.getFeatures(fieldWriter.features),参照 FieldWriterEnum.java:336 的合并写法),并明确/文档化 null 值是否对过滤器可见;过滤链(568-599)的拦截语义保持不变;ObjectWriterImplMap.java:151 的 context-only 写法属非字段上下文,不动。

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

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 966050d94.

The pre-skip now merges the field features — (jsonWriter.getFeatures(fieldWriter.features) & WriteNulls.mask) == 0 — so a field-level WriteNulls survives the filtered path exactly as it survives the no-filter fast path. A null value that survives is visible to the filter chain (the name/value filters see it like any other value); that is noted in the code comment, and ObjectWriterImplMap's context-only gate is untouched.

Issue7773#fieldLevelWriteNullsSurvivesFilters serializes ForcedNulls through a pass-through PropertyFilter on both creators and asserts all ten fields are present, plus the unannotated control ({} with the same filter).

中文说明

已在 966050d94 修复。预跳过判断现在合并字段特性——(jsonWriter.getFeatures(fieldWriter.features) & WriteNulls.mask) == 0——字段级 WriteNulls 在带过滤器的路径上与无过滤器快速路径一样生效。存活下来的 null 值对过滤器链可见(name/value 过滤器像看待其他值一样看到它),代码注释中已说明;ObjectWriterImplMap 的 context-only 写法未动。

Issue7773#fieldLevelWriteNullsSurvivesFilters 在两个 creator 上通过透传 PropertyFilter 序列化 ForcedNulls,断言十个字段全部存在,并带未注解对照组(同样过滤器下为 {})。

return;
}
writeFieldName(jsonWriter);
Expand Down Expand Up @@ -633,7 +633,7 @@ public void writeBinary(JSONWriter jsonWriter, byte[] value) {
}

public void writeInt16(JSONWriter jsonWriter, short[] value) {
if (value == null && !jsonWriter.isWriteNulls()) {
if (value == null && (jsonWriter.getFeatures(this.features) & WriteNulls.mask) == 0) {
return;
}

Expand Down Expand Up @@ -683,7 +683,7 @@ public void writeString(JSONWriter jsonWriter, String value) {
}

public void writeString(JSONWriter jsonWriter, char[] value) {
if (value == null && !jsonWriter.isWriteNulls()) {
if (value == null && (jsonWriter.getFeatures(this.features) & WriteNulls.mask) == 0) {
return;
}

Expand Down Expand Up @@ -728,7 +728,7 @@ public void writeBool(JSONWriter jsonWriter, boolean value) {
}

public void writeBool(JSONWriter jsonWriter, boolean[] value) {
if (value == null && !jsonWriter.isWriteNulls()) {
if (value == null && (jsonWriter.getFeatures(this.features) & WriteNulls.mask) == 0) {
return;
}

Expand All @@ -741,7 +741,7 @@ public void writeBool(JSONWriter jsonWriter, boolean[] value) {
}

public void writeFloat(JSONWriter jsonWriter, float[] value) {
if (value == null && !jsonWriter.isWriteNulls()) {
if (value == null && (jsonWriter.getFeatures(this.features) & WriteNulls.mask) == 0) {
return;
}

Expand All @@ -754,7 +754,7 @@ public void writeFloat(JSONWriter jsonWriter, float[] value) {
}

public void writeDouble(JSONWriter jsonWriter, double[] value) {
if (value == null && !jsonWriter.isWriteNulls()) {
if (value == null && (jsonWriter.getFeatures(this.features) & WriteNulls.mask) == 0) {

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] R1-6: field-level WriteNulls now overrides context NotWriteDefaultValue for the array/enum/int[]/long[] gates this diff makes unconditional, but the String null gate (ObjectWriterCreatorASM ~4267) and boxed Double/Float (FieldWriter.writeDouble(Double) ~769-776) still suppress on context NotWriteDefaultValue — the same annotation yields per-type divergent output under one context feature.

A bean with field-level WriteNulls on both byte[] bin and String name, serialized with context NotWriteDefaultValue → {"bin":null} with name dropped: whether an annotated null field appears depends on its declared type. (Verifier note: base reflect output is byte-identical — this split is a pre-existing reflect convention the diff propagates, while moving ASM into agreement with reflect for the covered types.)

Witness (probe on PR head):

C-F6 asm/reflect : {"bin":null,"dateField":null,"enumField":null,"longArr":null}   // strField dropped

Suggested fix: pick one policy for field-level WriteNulls vs context NotWriteDefaultValue and apply it to all the null gates this diff touches and the String/boxed gates. The fix must respect: the generated prologue deliberately forces WRITE_NULLS = 0 under context NotWriteDefaultValue (5109-5115) — preserve or consciously change that context-level coupling; contextWriteNullsStillWorks must stay green.

Acceptance criterion: an Issue7773 test writing a WriteNulls byte[] and a WriteNulls String under context NotWriteDefaultValue asserting the chosen uniform outcome — RED today either way; worth pinning once the policy is picked.

中文说明

字段级 WriteNulls 在本 PR 改为无条件的 array/enum/int[]/long[] 门上现在能压过 context 的 NotWriteDefaultValue,但 String 判空门(约 4267 行)与装箱 Double/Float(FieldWriter.writeDouble(Double) 约 769-776 行)仍会被 context NotWriteDefaultValue 抑制——同一注解在同一个 context 特性下按字段类型给出不同输出:byte[] bin 写出 {"bin":null} 而 String name 被丢弃(实测见上)。(验证注:修复前 reflect 输出逐字节相同——这是本 PR 沿袭的 reflect 既有约定;对已覆盖类型,ASM 是被本 PR 带到与 reflect 一致的。)

建议:为「字段级 WriteNulls vs context NotWriteDefaultValue」选一个统一策略,同时应用到本 PR 触及的所有判空门与 String/装箱门。约束:生成期序言在 context NotWriteDefaultValue 下刻意把 WRITE_NULLS 强制为 0(5109-5115)——保留或有意识地修改这一耦合;contextWriteNullsStillWorks 必须保持绿。

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

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.

Verified empirically rather than by policy: under a context NotWriteDefaultValue both creators now produce byte-identical output for every fixture, including the per-type split you describe — byte[]/enum/arrays/boxed Double are written, the String is dropped, identically in ASM and reflect:

WN + context NWDV   asm == reflect : {"byteArr":null,"enumField":null,"intArr":null,"longArr":null}

So this diff did not introduce a new convention; it moved ASM onto reflect's existing one, and the two now agree on both sides of the split. Changing the String/boxed policy would change the reflect creator's output for existing users — a semantic decision beyond #7773. I pinned the current parity instead (asmAndReflectCreatorsAgree covers BoxedUnderNotWriteDefaultValue under NotWriteDefaultValue); if you want a specific policy picked here, name it and I will implement it on both sides.

中文说明

用实测而非策略选择来回应:在 context NotWriteDefaultValue 下,两个 creator 对每个 fixture 的输出现在逐字节一致,包括你描述的分型差异——byte[]/enum/数组/装箱 Double 写出,String 丢弃,ASM 与 reflect 完全相同(实测见上)。

也就是说本 PR 没有引入新约定,只是把 ASM 搬到 reflect 既有约定上,现在分裂的两侧都一致。改 String/装箱策略会改变 reflect creator 对现有用户的输出——那是超出 #7773 的语义决策。我选择钉住当前 parity(asmAndReflectCreatorsAgree 覆盖 NotWriteDefaultValue 下的 BoxedUnderNotWriteDefaultValue);如果你要在这里选定某个策略,告诉我,我在两侧一起实现。

return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2552,8 +2552,10 @@ private void gwFieldValueEnum(
mw.visitLabel(null_);

// if (!jw.isWriteNulls())
mw.iload(mwc.var(WRITE_NULLS));
mw.ifeq(notNull_);
if ((fieldWriter.features & (WriteNulls.mask | NullAsDefaultValue.mask)) == 0) {

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.

[Critical] R1-1: [certifies-falsely] [regression] Field-level NullAsDefaultValue admitted by the new generation-time guards is interpreted inconsistently — this PR newly breaks ASM/reflect parity for enum fields and emits a contract-contradicting value for int[]/long[].

The three new guards union NullAsDefaultValue.mask into the field-level write-null decision, but the machinery that interprets the admitted bit was not aligned:

  1. enum — FieldWriterEnum.write (FieldWriterEnum.java:336) gates on WriteNulls.mask only, so a null enum field annotated serializeFeatures = NullAsDefaultValue is now written by ASM ("enumField":null) but omitted by reflect. Before this PR both creators omitted it (the context-only WRITE_NULLS var is 0) — they agreed; this diff is what breaks parity.
  2. int[]/long[] — the admitted branch calls no-arg writeArrayNull(), which resolves []-vs-null from context features only (JSONWriter.java:2191), so ASM emits "longArr":null where reflect (which merges field features into the context) emits "longArr":[] — the emitted value contradicts writeArrayNull's own contract.
  3. six array types — writeBinary/writeInt16/writeString(char[])/writeBool/writeFloat/writeDouble keep the WriteNulls-only mask, so byte[]/short[]/char[]/boolean[]/float[]/double[] with the same annotation are still dropped while int[]/long[]/enum are written — one annotation, per-type outcomes within a single serialization.
  4. WriteNullListAsEmpty.mask is absent from all three new masks (reflect's array gates include it).

Failure scenario (default creator, no context features) — a bean with @JSONField(serializeFeatures = JSONWriter.Feature.NullAsDefaultValue) on null fields MyEnum enumField, int[] intArr, long[] longArr, byte[] byteArr:

  • ASM: {"enumField":null,"intArr":null,"longArr":null} — byteArr silently dropped
  • reflect: enum omitted, all arrays as []

Same annotated bean, creator-dependent JSON — exactly the silent-divergence class issue #7773 reports, and this PR's own test javadoc says "the two creators must agree". The new asmAndReflectCreatorsAgree test covers only WriteNulls/NotWriteDefaultValue, so the divergence ships green.

Witness (probe on PR head vs merge base, both arms compiled):

PR   A-NAD asm     : {"enumField":null,"intArr":null,"longArr":null}
PR   A-NAD reflect : {"boolArr":[],"byteArr":[],"charArr":[],"doubleArr":[],"floatArr":[],"intArr":[],"longArr":[],"shortArr":[]}  (enum omitted)
BASE A-NAD asm     : {}   (both creators agreed pre-diff)

Suggested fix — align all sites on one field-level policy:

  • enum: widen FieldWriterEnum.write's null gate to WriteNulls | NullAsDefaultValue (matching the FieldWriterObject precedent), or narrow the ASM enum gate to WriteNulls.mask — either side, but one behavior;
  • int[]/long[]: emit the null via writeArrayNull(long) with context|field features merged — the established template is gwFieldValueList (ObjectWriterCreatorASM.java:3068-3078);
  • the six FieldWriter methods: widen the mask similarly (and consider WriteNullListAsEmpty + the features-aware writeArrayNull(long));
  • add NullAsDefaultValue fixtures + creator-parity assertions to Issue7773.

The fix must not violate: unannotated fields keep current output (unannotatedNullsRemainOmitted pins {}; contextWriteNullsStillWorks pins context WriteNulls), field-level WriteNulls keeps writing JSON null rather than [] (fieldLevelWriteNullsOnPrimitiveArraysAndEnum asserts assertNull), and generated bytecode for unannotated fields stays byte-identical (guards are only skipped when the mask is non-zero).

Acceptance criterion: an Issue7773 test with NullAsDefaultValue on enum + int[] + byte[] asserting writeWith(ObjectWriterCreator.INSTANCE, bean).equals(writeWith(ObjectWriterCreatorASM.INSTANCE, bean)) must be RED against this diff today and green after the fix — please remove one guard and confirm it reds.

中文说明

新增的生成期守卫把字段级 NullAsDefaultValue 并入判空决策,但解读该比特的周边机制没有对齐,导致同一注解下两个 creator 输出不一致:

  1. enum:FieldWriterEnum.write(336 行)只认 WriteNulls.mask,ASM 现在写出 "enumField":null 而 reflect 整字段省略;修复前两者都省略(一致),本 PR 新造了分歧。
  2. int[]/long[]:新分支调用无参 writeArrayNull(),只按 context 特性决定 [] 还是 null,ASM 输出 "longArr":null 而 reflect(合并字段特性后)输出 "longArr":[],与 writeArrayNull 自身契约矛盾。
  3. 六种数组:writeBinary/writeInt16/writeString(char[])/writeBool/writeFloat/writeDouble 仍是 WriteNulls 单掩码,同样注解下 byte[] 等仍被丢弃而 int[]/long[]/enum 被写出——同一次序列化内按字段类型分歧。
  4. 三个新掩码都缺 WriteNullListAsEmpty.mask(reflect 的数组门包含它)。

实测(PR 头 vs merge base 双臂编译):ASM {"enumField":null,"intArr":null,"longArr":null};reflect enum 省略、数组为 [];修复前 ASM {}(两者一致)。新测试 asmAndReflectCreatorsAgree 只覆盖 WriteNulls/NotWriteDefaultValue,所以该分歧未被测试发现。

建议:统一字段级策略——enum 侧对齐(拓宽 FieldWriterEnum 或收窄 ASM enum 门);int[]/long[] 用 writeArrayNull(long) 合并 context|field 特性(参照 gwFieldValueList 3068-3078 既有模板);六个 FieldWriter 方法同步放宽掩码;并在 Issue7773 补 NullAsDefaultValue 注解 + creator 一致性断言。

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

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 966050d94.

The enum gate is narrowed back to WriteNulls: FieldWriterEnum.write gates on WriteNulls only, so admitting NullAsDefaultValue on the ASM side wrote "enumField":null while reflect omits it — both creators now omit it, exactly as on the merge base. For int[]/long[] and the six FieldWriter array methods the null branch now writes through writeArrayNull(context | field) under one family mask (FieldWriter.ARRAY_NULL_FEATURES = WriteNulls | NullAsDefaultValue | WriteNullListAsEmpty) — the same merge FieldWriterObject#write performs, so NullAsDefaultValue/WriteNullListAsEmpty write [] and WriteNulls writes null, identically in both creators.

Measured on the new head (both creators, no context features):

NAD    asm == reflect : {"byteArr":[],"intArr":[],"longArr":[]}   (enum omitted on both)
WNLAE  asm == reflect : {"intArr":[],"longArr":[]}
WN     asm == reflect : all five fields null

Issue7773 pins this per creator (nullAsDefaultValueWritesEmptyArraysOnBothCreators, writeNullListAsEmptyWritesEmptyArraysOnBothCreators, asmAndReflectCreatorsAgree); removing the merge from either side reds them. Unannotated fields keep the previous output and bytecode (the guard is skipped when the mask is zero), and field-level WriteNulls still writes JSON null, not [].

中文说明

已在 966050d94 修复。enum 门收窄回 WriteNulls:FieldWriterEnum.write 本来就只认 WriteNulls,ASM 侧放进 NullAsDefaultValue 会写出 "enumField":null 而 reflect 省略——现在两侧都省略,与 merge base 一致。int[]/long[] 与六个 FieldWriter 数组方法的判空分支改为在统一家族掩码(FieldWriter.ARRAY_NULL_FEATURES)下调用 writeArrayNull(context | field),与 FieldWriterObject#write 的合并方式相同:NullAsDefaultValue/WriteNullListAsEmpty 写 [],WriteNulls 写 null,两个 creator 完全一致(实测见上)。

Issue7773 按 creator 分别钉住(nullAsDefaultValueWritesEmptyArraysOnBothCreators、writeNullListAsEmptyWritesEmptyArraysOnBothCreators、asmAndReflectCreatorsAgree),任一侧去掉合并都会变红。未注解字段的输出与字节码不变(掩码为 0 时守卫被跳过),字段级 WriteNulls 仍然写 JSON null 而不是 []。

mw.iload(mwc.var(WRITE_NULLS));
mw.ifeq(notNull_);
}

// writeFieldName(w);
gwFieldName(mwc, fieldWriter, i);
Expand Down Expand Up @@ -3978,10 +3980,12 @@ private void gwFieldValueInt64VA(

mw.ifnonnull(notNull_);

mw.iload(mwc.var(WRITE_NULLS));
mw.ifne(writeNullValue_);
if ((fieldWriter.features & (WriteNulls.mask | NullAsDefaultValue.mask)) == 0) {

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] R1-4: the same-file sibling gwFieldValueDate (line 3575) keeps a WriteNulls-only bake while this diff widens enum/int[]/long[] to WriteNulls | NullAsDefaultValue — and the new array-site masks also omit WriteNullListAsEmpty.mask, which reflect's array gates include (FieldWriterObject.java:322-333).

Consequence: one bean with NullAsDefaultValue on Date dateField and long[] longArr, both null → ASM writes "longArr":null but silently drops dateField within a single serialization; WriteNullListAsEmpty on int[]/long[] is likewise dropped by ASM while reflect writes []. (Verifier note: reflect drops the Date under the same annotation too — the Date split pre-exists on the reflect side; this diff widens it on the ASM side.)

Witness (probe on PR head):

A-NAD asm     : {"enumField":null,"intArr":null,"longArr":null}   // dateField absent
WNLAE reflect : {"intArr":[],"longArr":[]}
WNLAE asm     : {}

Suggested fix: widen gwFieldValueDate's guard to WriteNulls | NullAsDefaultValue for parity with the guards this diff adds, and use the type-appropriate family mask (including WriteNullListAsEmpty for arrays) at the new sites. Keep the guard shape if ((fieldWriter.features & MASK) == 0) { emit runtime check } so context-only serialization keeps its path through the WRITE_NULLS var (genMethodInit 5109-5122).

Acceptance criterion: an Issue7773 fixture with NullAsDefaultValue on Date and long[] asserting both are treated the same — RED without the widening; please revert one mask and confirm it reds.

中文说明

同文件的兄弟生成点 gwFieldValueDate(3575 行)仍是 WriteNulls 单掩码,而本 PR 把 enum/int[]/long[] 拓宽为 WriteNulls | NullAsDefaultValue;且新数组掩码都缺 WriteNullListAsEmpty.mask(reflect 的数组门包含它,见 FieldWriterObject.java:322-333)。后果:同一个 bean 里 Date 与 long[] 挂同样注解,ASM 写出 "longArr":null 却静默丢弃 dateField;int[]/long[] 挂 WriteNullListAsEmpty 时 ASM 省略而 reflect 写 [](实测见上)。(验证注:reflect 侧对 Date 同样丢弃——该分歧在 reflect 侧早已存在,本 PR 在 ASM 侧将其扩大。)

建议:把 gwFieldValueDate 的守卫拓宽到 WriteNulls | NullAsDefaultValue,新掩码按类型补齐家族掩码(数组含 WriteNullListAsEmpty);保持 if ((fieldWriter.features & MASK) == 0) { 生成运行期检查 } 的守卫形态,使 context-only 序列化仍走 WRITE_NULLS 变量(genMethodInit 5109-5122)。

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

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 WriteNullListAsEmpty half is fixed in 966050d94 — the new masks include it, so int[]/long[]/byte[]/... with that annotation write [] in ASM as they do in reflect (writeNullListAsEmptyWritesEmptyArraysOnBothCreators).

On gwFieldValueDate I deliberately kept the WriteNulls-only bake: your own verifier note says the reflect creator drops a NullAsDefaultValue Date too, so widening the ASM gate would make ASM write "dateField":null while reflect drops it — widening breaks the parity rather than restoring it. With the array masks above, one bean with NullAsDefaultValue on Date and long[] now behaves identically in both creators: {"dateField2":null,"longArr":[]} — the NullAsDefaultValue Date is dropped, the WriteNulls Date is written, the array is []. Issue7773#dateFieldNullGateStaysInSyncAcrossCreators pins that per creator.

If you want the Date split itself closed (Date honoring NullAsDefaultValue on both sides), that is a reflect-side semantic change and I would do it as a separate PR.

中文说明

WriteNullListAsEmpty 一半已在 966050d94 修复:新掩码包含它,带该注解的 int[]/long[]/byte[] 等在 ASM 下与 reflect 一样写 [](writeNullListAsEmptyWritesEmptyArraysOnBothCreators)。

gwFieldValueDate 我有意保留 WriteNulls 单掩码:你的验证注记也说 reflect 侧同样丢弃挂 NullAsDefaultValue 的 Date,拓宽 ASM 门会让 ASM 写出 "dateField":null 而 reflect 丢弃——拓宽是破坏 parity 而不是恢复。配合上面的数组掩码,同一个 bean(Date 与 long[] 都挂 NullAsDefaultValue)现在两侧输出一致:{"dateField2":null,"longArr":[]}——NAD 的 Date 丢弃、WriteNulls 的 Date 写出、数组写 []。Issue7773#dateFieldNullGateStaysInSyncAcrossCreators 按 creator 钉住。

如果你希望连 Date 的分歧一并收掉(两侧都让 Date 遵循 NullAsDefaultValue),那是 reflect 侧的语义变更,我会单独开 PR。

mw.iload(mwc.var(WRITE_NULLS));
mw.ifne(writeNullValue_);

mw.goto_(endIfNull_);
mw.goto_(endIfNull_);
}

mw.visitLabel(writeNullValue_);

Expand Down Expand Up @@ -4029,8 +4033,10 @@ private void gwFieldValueInt64V(
mw.ifne(notDefaultValue_);

if (fieldWriter.defaultValue == null) {
mw.iload(WRITE_DEFAULT_VALUE);
mw.ifeq(notDefaultValue_);
if ((fieldWriter.features & NotWriteDefaultValue.mask) == 0) {

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] R1-2: the parity fix is applied only to the text-JSON generators — the JSONB twin still consults context-only runtime vars, so field-level serializeFeatures remain dead in JSONB.

genMethodWriteJSONB gates null-writing on iload(mwc.var(WRITE_NULLS)) (line 1178) and primitives on WRITE_DEFAULT_VALUE (1192-1202), never on fieldWriter.features. Consequence: a WriteNulls-annotated null field serializes as "name":null in text JSON but is omitted via JSONWriter.ofJSONB(); a NotWriteDefaultValue zero primitive is omitted in text but written as "count":0 in JSONB — the same bean serializes differently by output format. (The PR changed only the text side; for the Defaults shape both sides previously agreed, both writing the zeros.)

Witness (probe on PR head):

D-F2 WriteNulls text  : {"bin":null,"dateField":null,"enumField":null,"longArr":null,"strField":null}
D-F2 WriteNulls jsonb : {}
D-F2 Defaults   text  : {"control":7}
D-F2 Defaults   jsonb : {"control":7,"count":0,"size":0}

Suggested fix: apply the same generation-time guards inside genMethodWriteJSONB, guarding the whole name+value block — the name goes through gwFieldNameDirectJSONB directly into the byte buffer at 1183, so the guard cannot gate only the value. The fix must respect the block's structure: the writeFieldName guard (1175), the fieldWriter.defaultValue == null guard (1176), and the ReferenceDetection/endDetect_ ordering (1127-1177).

Acceptance criterion: an Issue7773 JSONB round-trip test asserting the Defaults-style zero fields are absent and the ForcedNulls-style null fields present — RED before the fix; please remove the guard and confirm it reds.

中文说明

parity 修复只应用到文本 JSON 生成器:JSONB 生成器 genMethodWriteJSONB(1178 行判空、1192-1202 行基本类型)仍只读 context 运行期变量,从不看 fieldWriter.features,字段级 serializeFeatures 在 JSONB 下依旧无效。于是同一个 bean 按输出格式产生不同结果:WriteNulls 注解的 null 字段文本 JSON 写 "name":null、JSONB 省略;NotWriteDefaultValue 注解的零值基本类型文本 JSON 省略、JSONB 写 "count":0(实测见上)。本 PR 只改了文本侧;对 Defaults 形态,修复前两侧是一致(都写零值)的。

建议:在 genMethodWriteJSONB 内加同样的生成期守卫,且必须包住「字段名+值」整块(字段名经 gwFieldNameDirectJSONB 在 1183 行直接写入缓冲,守卫不能只挡值);保持 1175/1176 两层外层守卫与 1127-1177 的 ReferenceDetection 顺序不变。

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

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 966050d94.

genMethodWriteJSONB's guards now bake the field-level features: a non-primitive field with a field-level WriteNulls keeps the whole name+value block (the guard sits before gwFieldNameDirectJSONB, so the block is gated, not just the value), and a default primitive with a field-level NotWriteDefaultValue is dropped — mirroring the gwFieldValueInt64V/gwFieldValueInt32V bakes. The same shape you did not list: the direct JSONB branch had no guard for float/double at all, so zero float/double were always written there; now covered.

Measured:

Defaults    text  asm == reflect : {"control":7}
Defaults    jsonb asm == reflect : {"control":7}
ForcedNulls jsonb asm == reflect : all ten fields null

Issue7773#fieldLevelFeaturesWorkInJsonb / jsonbCreatorsAgree pin it. One extra crash this exposed: a null enum in the direct JSONB path went through JSONB.IO.writeEnum, which dereferences the value — with a field-level WriteNulls (and, pre-existing on main, with a context WriteNulls) that NPE'd while reflect wrote "enumField":null. The null now writes BC_NULL directly; the reference-detection / endDetect_ ordering and the two outer guards are unchanged.

中文说明

已在 966050d94 修复。genMethodWriteJSONB 的守卫现在烘焙字段级特性:带字段级 WriteNulls 的非基本类型字段保留整个「字段名+值」块(守卫位于 gwFieldNameDirectJSONB 之前,挡的是整块而不只是值);带字段级 NotWriteDefaultValue 的零值基本类型直接跳过——与 gwFieldValueInt64V/gwFieldValueInt32V 的烘焙一致。另外补了一个同形态但你没列到的洞:direct JSONB 分支对 float/double 完全没有守卫,零值总会被写出,现已覆盖。

实测见上(Defaults 在文本与 JSONB 下两侧一致;ForcedNulls 在 JSONB 下十个字段都以 null 写出)。Issue7773#fieldLevelFeaturesWorkInJsonb / jsonbCreatorsAgree 钉住。顺带修了一个崩溃:direct JSONB 路径下 null enum 会走 JSONB.IO.writeEnum(解引用 value)——字段级 WriteNulls(以及 main 上已有的 context WriteNulls)会触发 NPE,而 reflect 写 "enumField":null;现在 null 直接写 BC_NULL,ReferenceDetection/endDetect_ 顺序与两层外层守卫未动。

mw.iload(WRITE_DEFAULT_VALUE);
mw.ifeq(notDefaultValue_);
}
mw.goto_(endWriteValue_);
}
mw.visitLabel(notDefaultValue_);
Expand Down Expand Up @@ -4081,10 +4087,12 @@ void gwFieldValueIntVA(

mw.ifnonnull(notNull_);

mw.iload(mwc.var(WRITE_NULLS));
mw.ifne(writeNullValue_);
if ((fieldWriter.features & (WriteNulls.mask | NullAsDefaultValue.mask)) == 0) {

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] R1-5: the "should this field's null be written" decision is hand-rolled at 14+ sites across the generator and FieldWriter layers with 6+ distinct mask spellings — this PR adds three more spellings and patches the six sites its issue hit; the next field-type report will be another 3-line paste.

Sweep at PR head (verification): new sites 2555/3983/4090 (WriteNulls|NullAsDefaultValue), Date 3574 (WriteNulls), boxed 3158/3229/3301/3375 (WriteNulls|NullAsDefaultValue|WriteNullNumberAsZero), String 4250-4275 (generation-time bake + runtime genIsEnabled/genIsDisabled), List 3068 (runtime genIsEnabled, includes WriteNullListAsEmpty), JSONB 1178 + 5114-5122 (runtime vars), FieldWriterEnum 336 (WriteNulls only), FieldWriterObject 341-355 (family-specific merged), FieldWriterObjectArray 116, FieldWriter 594-757 (six copies), ObjectWriterAdapter 602/777. R1-1 is this drift materializing within one PR.

Concrete cost: every future "feature X ignored for field type Y" report is a fresh per-site edit re-deciding the mask, and reviewers must diff six conventions to check one behavior.

Suggested fix: extract one generator helper (e.g. genWriteNullGuard(mwc, fieldWriter, ...)) owning the agreed feature set and the bake-vs-runtime-var choice, called from every gwFieldValueXxx null branch — including the untouched Date/Object/String/List ones; on the FieldWriter side one shouldWriteNull(JSONWriter) helper instead of six copies. Keep it allocation-free and tiny (the project's codeSize / JIT inlining budgets apply). The bake must remain a generation-time constant-fold on fieldWriter.features (the runtime var is per-writer, computed once in genMethodInit), and the refactor must not change the emitted bytecode semantics of the six sites this PR touched.

Acceptance criterion: the R1-1 agreement test stays green through the extraction, unannotatedNullsRemainOmitted stays green, and reintroducing any per-site mask drift fails the agreement test — worth pinning before this pattern copies itself further.

中文说明

「该字段的 null 要不要写」这一决策在生成器与 FieldWriter 两层共 14+ 处手写、6+ 种掩码拼法(验证阶段全量清点见上:新站点 2555/3983/4090、Date 3574、装箱 3158/3229/3301/3375、String 4250-4275、List 3068、JSONB 1178+5114-5122、FieldWriterEnum 336、FieldWriterObject 341-355、FieldWriterObjectArray 116、FieldWriter 594-757 六份拷贝、ObjectWriterAdapter 602/777)。本 PR 又新增三种拼法、只修了 issue 命中的六处;R1-1 正是这种漂移在同一 PR 内的现实化。代价:以后每份「特性 X 对字段类型 Y 无效」的报告都是一次新的逐点补丁,评审者要对比六种约定才能确认一个行为。

建议:抽取一个生成期 helper(如 genWriteNullGuard(mwc, fieldWriter, ...))统一持有特性集合与 bake/运行期变量 的选择,供所有 gwFieldValueXxx 判空分支调用(含未改动的 Date/Object/String/List);FieldWriter 侧用一个 shouldWriteNull(JSONWriter) 替代六份拷贝。保持无分配、足够小(项目对 codeSize / JIT 内联有预算要求);bake 必须保持对 fieldWriter.features 的生成期常量折叠(运行期变量是 per-writer、在 genMethodInit 一次算定),且不得改变本 PR 所改六处生成字节码的语义。

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

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.

Partially addressed, and I want to be explicit about the part I did not do.

Done: the array-null family now has exactly one spelling — FieldWriter.ARRAY_NULL_FEATURES — referenced by the six FieldWriter methods and by both ASM array sites, so the drift that produced R1-1 cannot recur for that family without redding asmAndReflectCreatorsAgree.

Not done: the full genWriteNullGuard extraction across the 14+ sites. Your own constraint is that it must not change the emitted bytecode of the touched sites, and a mechanical extraction across the Date/Object/String/List/JSONB sites — including the bake-vs-runtime-var choice — deserves its own review pass rather than being folded into a bug-fix PR. I would do it as a follow-up against this branch once this one lands; the agreement tests here are the safety net for exactly that refactor.

中文说明

部分落实,未落实的部分说明清楚。已做:数组判空家族现在只有一种拼法——FieldWriter.ARRAY_NULL_FEATURES``——六个 FieldWriter方法与两个 ASM 数组站点都引用它,该家族再发生 R1-1 这类漂移必然让asmAndReflectCreatorsAgree` 变红。

未做:跨 14+ 处抽取 genWriteNullGuard。你自己的约束是「不得改变已触碰站点生成字节码的语义」,而一次覆盖 Date/Object/String/List/JSONB 各站点的机械抽取(含 bake 与运行期变量的选择)值得单独一轮 review,不适合并进修 bug 的 PR。我会在本 PR 合入后基于该分支做后续 PR;这里的各类一致性测试正是那次重构的安全网。

mw.iload(mwc.var(WRITE_NULLS));
mw.ifne(writeNullValue_);

mw.goto_(endIfNull_);
mw.goto_(endIfNull_);
}

mw.visitLabel(writeNullValue_);

Expand Down Expand Up @@ -4132,8 +4140,10 @@ private void gwFieldValueInt32V(
mw.ifne(notDefaultValue_);

if (fieldWriter.defaultValue == null) {
mw.iload(WRITE_DEFAULT_VALUE);
mw.ifeq(notDefaultValue_);
if ((fieldWriter.features & NotWriteDefaultValue.mask) == 0) {
mw.iload(WRITE_DEFAULT_VALUE);
mw.ifeq(notDefaultValue_);
}
mw.goto_(endWriteValue_);
}
mw.visitLabel(notDefaultValue_);
Expand Down Expand Up @@ -4165,8 +4175,10 @@ private void gwFieldValueBooleanV(
mw.ifne(notDefaultValue_);

if (fieldWriter.defaultValue == null) {
mw.iload(WRITE_DEFAULT_VALUE);
mw.ifeq(notDefaultValue_);
if ((fieldWriter.features & NotWriteDefaultValue.mask) == 0) {
mw.iload(WRITE_DEFAULT_VALUE);
mw.ifeq(notDefaultValue_);
}
mw.goto_(endWriteValue_);
}
mw.visitLabel(notDefaultValue_);
Expand Down
169 changes: 169 additions & 0 deletions core/src/test/java/com/alibaba/fastjson2/issues_7000/Issue7773.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
package com.alibaba.fastjson2.issues_7000;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.annotation.JSONField;
import com.alibaba.fastjson2.writer.ObjectWriter;
import com.alibaba.fastjson2.writer.ObjectWriterCreator;
import com.alibaba.fastjson2.writer.ObjectWriterCreatorASM;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
* A field level {@code @JSONField(serializeFeatures = ...)} must be honoured by the ASM generated
* ObjectWriter exactly as it is by the reflect one. Before the fix the ASM generator only looked at
* the writer context, so:
* <ul>
* <li>{@code WriteNulls} was ignored for primitive arrays and for enum fields</li>
* <li>{@code NotWriteDefaultValue} was ignored for primitive value fields</li>
* </ul>
* Both are compile time constants of the generated writer, so the two creators must agree.
*/
public class Issue7773 {
public enum MyEnum {
A, B
}

public static class ForcedNulls {
@JSONField(serializeFeatures = JSONWriter.Feature.WriteNulls)
public int[] intArr;
@JSONField(serializeFeatures = JSONWriter.Feature.WriteNulls)
public long[] longArr;
@JSONField(serializeFeatures = JSONWriter.Feature.WriteNulls)
public boolean[] boolArr;
@JSONField(serializeFeatures = JSONWriter.Feature.WriteNulls)
public short[] shortArr;
@JSONField(serializeFeatures = JSONWriter.Feature.WriteNulls)
public byte[] byteArr;
@JSONField(serializeFeatures = JSONWriter.Feature.WriteNulls)
public char[] charArr;
@JSONField(serializeFeatures = JSONWriter.Feature.WriteNulls)
public double[] doubleArr;
@JSONField(serializeFeatures = JSONWriter.Feature.WriteNulls)
public float[] floatArr;
@JSONField(serializeFeatures = JSONWriter.Feature.WriteNulls)
public MyEnum enumField;
@JSONField(serializeFeatures = JSONWriter.Feature.WriteNulls)
public String strField;
}

public static class PlainNulls {
public int[] intArr;
public long[] longArr;
public boolean[] boolArr;
public short[] shortArr;
public byte[] byteArr;
public char[] charArr;
public double[] doubleArr;
public float[] floatArr;
public MyEnum enumField;
public String strField;
}

public static class Defaults {
@JSONField(serializeFeatures = JSONWriter.Feature.NotWriteDefaultValue)
public short duration;
@JSONField(serializeFeatures = JSONWriter.Feature.NotWriteDefaultValue)
public byte b;
@JSONField(serializeFeatures = JSONWriter.Feature.NotWriteDefaultValue)
public char c;
@JSONField(serializeFeatures = JSONWriter.Feature.NotWriteDefaultValue)
public int count;
@JSONField(serializeFeatures = JSONWriter.Feature.NotWriteDefaultValue)
public long size;
@JSONField(serializeFeatures = JSONWriter.Feature.NotWriteDefaultValue)
public boolean flag;
@JSONField(serializeFeatures = JSONWriter.Feature.NotWriteDefaultValue)
public float f;
@JSONField(serializeFeatures = JSONWriter.Feature.NotWriteDefaultValue)
public double d;
public int control = 7;
}

private static final String[] NULL_FIELDS = {
"intArr", "longArr", "boolArr", "shortArr", "byteArr",
"charArr", "doubleArr", "floatArr", "enumField", "strField"
};

private static final String[] DEFAULT_FIELDS = {
"duration", "b", "c", "count", "size", "flag", "f", "d"
};

@Test
public void fieldLevelWriteNullsOnPrimitiveArraysAndEnum() {
JSONObject object = JSON.parseObject(JSON.toJSONString(new ForcedNulls()));
for (String name : NULL_FIELDS) {
assertTrue(object.containsKey(name), "missing field : " + name);
assertNull(object.get(name), "unexpected value for field : " + name);
}
assertEquals(NULL_FIELDS.length, object.size());
}

@Test
public void unannotatedNullsRemainOmitted() {
assertEquals("{}", JSON.toJSONString(new PlainNulls()));
}

@Test
public void contextWriteNullsStillWorks() {
JSONObject object = JSON.parseObject(JSON.toJSONString(new PlainNulls(), JSONWriter.Feature.WriteNulls));
for (String name : NULL_FIELDS) {
assertTrue(object.containsKey(name), "missing field : " + name);
}
assertEquals(NULL_FIELDS.length, object.size());
}

@Test
public void fieldLevelNotWriteDefaultValueOnPrimitives() {
JSONObject object = JSON.parseObject(JSON.toJSONString(new Defaults()));
for (String name : DEFAULT_FIELDS) {
assertFalse(object.containsKey(name), "default value written for field : " + name);
}
assertEquals(1, object.size());
assertEquals(7, object.getIntValue("control"));
}

@Test
public void nonDefaultValuesAreStillWritten() {
Defaults bean = new Defaults();
bean.duration = 5;
bean.b = 6;
bean.c = 'x';
bean.count = 3;
bean.size = 4L;
bean.flag = true;
bean.f = 1.5F;
bean.d = 2.5D;

JSONObject object = JSON.parseObject(JSON.toJSONString(bean));
assertEquals(5, object.getIntValue("duration"));
assertEquals(6, object.getIntValue("b"));
assertEquals("x", object.getString("c"));
assertEquals(3, object.getIntValue("count"));
assertEquals(4L, object.getLongValue("size"));
assertTrue(object.getBooleanValue("flag"));
assertEquals(1.5F, object.getFloatValue("f"));
assertEquals(2.5D, object.getDoubleValue("d"));
assertEquals(7, object.getIntValue("control"));
}

@Test
public void asmAndReflectCreatorsAgree() {
assertEquals(
writeWith(ObjectWriterCreator.INSTANCE, new ForcedNulls()),
writeWith(ObjectWriterCreatorASM.INSTANCE, new ForcedNulls()));
assertEquals(
writeWith(ObjectWriterCreator.INSTANCE, new Defaults()),
writeWith(ObjectWriterCreatorASM.INSTANCE, new Defaults()));
}

private static String writeWith(ObjectWriterCreator creator, Object bean) {
ObjectWriter<Object> objectWriter = creator.createObjectWriter(bean.getClass());
return objectWriter.toJSONString(bean);
}
}
Loading