From 11098828f8a9c12789b5b2030a5fce6f48a0b368 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 15:42:12 +0100 Subject: [PATCH 1/4] feat(java): apply JSON SKIP null handling to codec-decoded nulls With onNullRead(SKIP) or onContentNullRead(SKIP), a Java null returned by the selected codec for a non-null JSON token is now treated like an explicit JSON null: the property keeps its current value (creator arguments stay absent), and the collection element, reference-array element, AtomicReferenceArray element, or map value is omitted. SET and FAIL are unchanged. Generated readers emit the null test only for SKIP properties, so default SET code is unchanged. Reference arrays compact decoded nulls after the read loop so graph-memory batch reservation stays ahead of each batch's final element. Co-Authored-By: Claude Opus 5.5 --- docs/json/annotations.md | 5 + docs/json/custom-codecs.md | 6 +- .../org/apache/fory/json/ForyJsonBuilder.java | 7 +- .../fory/json/annotation/JsonProperty.java | 13 +- .../apache/fory/json/codec/ArrayCodec.java | 25 +++ .../fory/json/codec/CollectionCodec.java | 30 +++- .../org/apache/fory/json/codec/MapCodec.java | 15 +- .../apache/fory/json/codec/ObjectCodec.java | 24 +-- .../apache/fory/json/codec/ScalarCodecs.java | 9 ++ .../fory/json/codegen/JsonReaderCodegen.java | 143 +++++++++++++----- .../fory/json/meta/JsonCreatorFieldInfo.java | 33 ++-- .../apache/fory/json/meta/JsonFieldInfo.java | 23 +-- .../fory/json/JsonNullHandlingTest.java | 141 ++++++++++++++++- 13 files changed, 387 insertions(+), 87 deletions(-) diff --git a/docs/json/annotations.md b/docs/json/annotations.md index 69deba4065..9a5303a2c2 100644 --- a/docs/json/annotations.md +++ b/docs/json/annotations.md @@ -234,6 +234,11 @@ Constructor parameters follow their existing missing-property defaults and requi checks. A skipped duplicate does not erase an earlier value: `{"seats":["a"],"seats":null}` keeps `"a"`. Constructor-bypassed objects have no initializer to preserve. +`SKIP` also applies when a selected codec returns Java null for a non-null JSON value. For example, +a trimming property codec that decodes `" "` to null leaves the current value unchanged, and a +trimming `elementCodec` omits that collection element. This covers property assignments, collection +and reference-array elements, and map values. `FAIL` still rejects only an explicit JSON null. + `SET` preserves codec behavior: null may become `Optional.empty()`, or fail for a primitive or non-null Kotlin value. `SKIP` and `FAIL` act before that decoding. Only the literal JSON null is affected; the string `"null"` and a custom codec returning Java null for another token are not diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index efa517df0f..04cbcbb0f1 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -130,8 +130,10 @@ is an array element, collection element, map value, Optional value, or atomic-re codec receives and owns null during writing. During reading, the codec owns null when the applicable read setting is `SET`. Property `onNullRead` and Fory container `onContentNullRead` settings intercept literal null before invoking a selected -child codec when configured as `SKIP` or `FAIL`. A codec returning Java null after consuming a -non-null token is not filtered. The registered instance is shared across concurrent operations and +child codec when configured as `SKIP` or `FAIL`. Under `SKIP`, a Java null returned after +consuming a non-null token is also omitted: the property keeps its current value, and the +collection element, reference-array element, or map value is not inserted. `SET` and `FAIL` assign +such a value normally. The registered instance is shared across concurrent operations and must be thread-safe. A complete custom container codec owns its internal representation, so the global content setting diff --git a/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java b/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java index 67a3b4a862..1ab3f72059 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java @@ -125,7 +125,8 @@ public ForyJsonBuilder defaultPropertyInclusion(Include inclusion) { * Sets the default handling of explicit JSON null property values. Defaults to {@code SET}. * Property {@link org.apache.fory.json.annotation.JsonProperty#onNullRead()} overrides it. {@code * SKIP} preserves the current field value or existing missing-creator-argument behavior; it does - * not fabricate defaults. Root null values and writing are unaffected. + * not fabricate defaults. {@code SKIP} also applies when the property's codec returns Java null + * for a non-null JSON token. Root null values and writing are unaffected. * * @throws IllegalArgumentException if handling is {@code DEFAULT} * @throws NullPointerException if handling is null @@ -140,7 +141,9 @@ public ForyJsonBuilder onNullRead(NullHandling handling) { * Sets the default handling of explicit null elements and map values in Fory-owned containers, * including root containers. Defaults to {@code SET}. Property {@link * org.apache.fory.json.annotation.JsonProperty#onContentNullRead()} overrides the immediate - * container's setting. Complete custom codecs retain their representation. Writing is unaffected. + * container's setting. {@code SKIP} also omits a Java null returned by a child codec for a + * collection or reference-array element or a map value. Complete custom codecs retain their + * representation. Writing is unaffected. * * @throws IllegalArgumentException if handling is {@code DEFAULT} * @throws NullPointerException if handling is null diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonProperty.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonProperty.java index 0661492486..aef29ad8f6 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonProperty.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonProperty.java @@ -88,7 +88,8 @@ * Returns how an explicit JSON null is read for this property. {@code DEFAULT} inherits the * builder setting. {@code SKIP} consumes the null without assigning the field, invoking a setter, * or marking a creator argument present; existing missing-property defaults and requirements - * still apply. This setting affects reading only. + * still apply. {@code SKIP} treats a Java null returned by the property's codec for a non-null + * JSON token the same way. This setting affects reading only. */ NullHandling onNullRead() default NullHandling.DEFAULT; @@ -97,8 +98,9 @@ * values are read. {@code SKIP} omits an element or map insertion. Nested containers resolve * their own settings. Explicit {@code SKIP} and {@code FAIL} require a container representation * owned by Fory; explicit {@code SET} also accepts a complete custom container codec. Encoded - * binary strings and non-container targets reject explicit settings. This does not filter values - * returned by a custom codec for non-null JSON tokens. + * binary strings and non-container targets reject explicit settings. {@code SKIP} also omits a + * Java null returned by the child codec of a collection, reference array, or map value for a + * non-null JSON token; {@code FAIL} rejects only explicit JSON null. */ NullHandling onContentNullRead() default NullHandling.DEFAULT; @@ -108,7 +110,10 @@ enum NullHandling { DEFAULT, /** Use the normal type and codec read/assignment, including existing nullability checks. */ SET, - /** Consume the null without assigning the property or inserting the container item. */ + /** + * Consume the null without assigning the property or inserting the container item. A Java null + * decoded from a non-null JSON token by the selected codec is treated the same way. + */ SKIP, /** Reject an explicit JSON null. Missing properties are unaffected. */ FAIL diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ArrayCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ArrayCodec.java index 1d6a21ed91..0416ba00d6 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ArrayCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ArrayCodec.java @@ -227,6 +227,22 @@ static void reserveReferenceBatch(JsonReader reader, int size) { } } + /** + * Removes nulls decoded by a reference element codec after SKIP already dropped explicit JSON + * nulls. Compacting after the loop keeps each batch reservation ahead of the batch's final + * element read; the reservation still covers every decoded element. + */ + static int removeDecodedNulls(Object[] values, int size) { + int kept = 0; + for (int i = 0; i < size; i++) { + Object value = values[i]; + if (value != null) { + values[kept++] = value; + } + } + return kept; + } + static void finishReferenceArray(JsonReader reader, int size) { int tailSize = size & ARRAY_BATCH_MASK; reader.reserveGraphMemory(ARRAY_HEADER_BYTES + tailSize * REFERENCE_BYTES); @@ -2716,6 +2732,9 @@ public T readLatin1(Latin1JsonReader reader) { } while (reader.consumeNextCommaOrEndArray()); } reader.reserveGraphMemory(ARRAY_HEADER_BYTES + (size & ARRAY_BATCH_MASK) * REFERENCE_BYTES); + if (onContentNullRead == NullHandling.SKIP) { + size = removeDecodedNulls(values, size); + } T array = (T) (size == values.length ? values : Arrays.copyOf(values, size)); reader.exitDepth(); return array; @@ -2748,6 +2767,9 @@ public T readUtf16(Utf16JsonReader reader) { } while (reader.consumeNextCommaOrEndArray()); } reader.reserveGraphMemory(ARRAY_HEADER_BYTES + (size & ARRAY_BATCH_MASK) * REFERENCE_BYTES); + if (onContentNullRead == NullHandling.SKIP) { + size = removeDecodedNulls(values, size); + } T array = (T) (size == values.length ? values : Arrays.copyOf(values, size)); reader.exitDepth(); return array; @@ -2780,6 +2802,9 @@ public T readUtf8(Utf8JsonReader reader) { } while (reader.consumeNextCommaOrEndArray()); } reader.reserveGraphMemory(ARRAY_HEADER_BYTES + (size & ARRAY_BATCH_MASK) * REFERENCE_BYTES); + if (onContentNullRead == NullHandling.SKIP) { + size = removeDecodedNulls(values, size); + } T array = (T) (size == values.length ? values : Arrays.copyOf(values, size)); reader.exitDepth(); return array; diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/CollectionCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/CollectionCodec.java index 02fdd5000c..8f7cb3a6b3 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codec/CollectionCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/CollectionCodec.java @@ -1162,7 +1162,10 @@ public Collection readLatin1(Latin1JsonReader reader) { if ((size & REFERENCE_BATCH_MASK) == REFERENCE_BATCH_MASK) { reader.reserveGraphMemory(REFERENCE_BATCH_BYTES); } - collection.add(requireElement(elementTypeInfo, codec.readLatin1(reader))); + Object element = codec.readLatin1(reader); + if (element != null || onContentNullRead != NullHandling.SKIP) { + collection.add(requireElement(elementTypeInfo, element)); + } size++; } while (reader.consumeNextCommaOrEndArray()); } @@ -1195,7 +1198,10 @@ public Collection readUtf16(Utf16JsonReader reader) { if ((size & REFERENCE_BATCH_MASK) == REFERENCE_BATCH_MASK) { reader.reserveGraphMemory(REFERENCE_BATCH_BYTES); } - collection.add(requireElement(elementTypeInfo, codec.readUtf16(reader))); + Object element = codec.readUtf16(reader); + if (element != null || onContentNullRead != NullHandling.SKIP) { + collection.add(requireElement(elementTypeInfo, element)); + } size++; } while (reader.consumeNextCommaOrEndArray()); } @@ -1228,7 +1234,10 @@ public Collection readUtf8(Utf8JsonReader reader) { if ((size & REFERENCE_BATCH_MASK) == REFERENCE_BATCH_MASK) { reader.reserveGraphMemory(REFERENCE_BATCH_BYTES); } - collection.add(requireElement(elementTypeInfo, codec.readUtf8(reader))); + Object element = codec.readUtf8(reader); + if (element != null || onContentNullRead != NullHandling.SKIP) { + collection.add(requireElement(elementTypeInfo, element)); + } size++; } while (reader.consumeNextCommaOrEndArray()); } @@ -1326,7 +1335,10 @@ public Collection readLatin1(Latin1JsonReader reader) { if ((size & REFERENCE_BATCH_MASK) == REFERENCE_BATCH_MASK) { reader.reserveGraphMemory(REFERENCE_BATCH_BYTES); } - collection.add(requireElement(elementTypeInfo, codec.readLatin1(reader))); + Object element = codec.readLatin1(reader); + if (element != null || onContentNullRead != NullHandling.SKIP) { + collection.add(requireElement(elementTypeInfo, element)); + } size++; } while (reader.consumeNextCommaOrEndArray()); } @@ -1362,7 +1374,10 @@ public Collection readUtf16(Utf16JsonReader reader) { if ((size & REFERENCE_BATCH_MASK) == REFERENCE_BATCH_MASK) { reader.reserveGraphMemory(REFERENCE_BATCH_BYTES); } - collection.add(requireElement(elementTypeInfo, codec.readUtf16(reader))); + Object element = codec.readUtf16(reader); + if (element != null || onContentNullRead != NullHandling.SKIP) { + collection.add(requireElement(elementTypeInfo, element)); + } size++; } while (reader.consumeNextCommaOrEndArray()); } @@ -1398,7 +1413,10 @@ public Collection readUtf8(Utf8JsonReader reader) { if ((size & REFERENCE_BATCH_MASK) == REFERENCE_BATCH_MASK) { reader.reserveGraphMemory(REFERENCE_BATCH_BYTES); } - collection.add(requireElement(elementTypeInfo, codec.readUtf8(reader))); + Object element = codec.readUtf8(reader); + if (element != null || onContentNullRead != NullHandling.SKIP) { + collection.add(requireElement(elementTypeInfo, element)); + } size++; } while (reader.consumeNextCommaOrEndArray()); } diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/MapCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/MapCodec.java index 14d6aec024..ea3ed99cb3 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codec/MapCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/MapCodec.java @@ -673,7 +673,10 @@ public void writeUtf8(Utf8JsonWriter writer, Map value) { if ((size & ENTRY_BATCH_MASK) == ENTRY_BATCH_MASK) { reader.reserveGraphMemory(ENTRY_BATCH_BYTES); } - map.put(key, readValue(reader, codec)); + Object value = readValue(reader, codec); + if (value != null || onContentNullRead != NullHandling.SKIP) { + map.put(key, value); + } size++; } while (reader.consumeNextToken(',')); reader.expectNextToken('}'); @@ -709,7 +712,10 @@ public void writeUtf8(Utf8JsonWriter writer, Map value) { if ((size & ENTRY_BATCH_MASK) == ENTRY_BATCH_MASK) { reader.reserveGraphMemory(ENTRY_BATCH_BYTES); } - map.put(key, readValue(reader, codec)); + Object value = readValue(reader, codec); + if (value != null || onContentNullRead != NullHandling.SKIP) { + map.put(key, value); + } size++; } while (reader.consumeNextToken(',')); reader.expectNextToken('}'); @@ -745,7 +751,10 @@ public void writeUtf8(Utf8JsonWriter writer, Map value) { if ((size & ENTRY_BATCH_MASK) == ENTRY_BATCH_MASK) { reader.reserveGraphMemory(ENTRY_BATCH_BYTES); } - map.put(key, readValue(reader, codec)); + Object value = readValue(reader, codec); + if (value != null || onContentNullRead != NullHandling.SKIP) { + map.put(key, value); + } size++; } while (reader.consumeNextToken(',')); reader.expectNextToken('}'); diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java index 66198884af..f7529b7799 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java @@ -906,7 +906,7 @@ private T readLatin1UnwrappedObject(Latin1JsonReader reader, JsonFieldTable dire } else { JsonCreatorFieldInfo field = creatorInfo.fields()[direct]; if (!field.skipNullRead(reader)) { - ((Object[]) rootWorkspace)[field.argumentIndex()] = field.readLatin1(reader); + field.readLatin1(reader, (Object[]) rootWorkspace); } } continue; @@ -986,7 +986,7 @@ private T readUtf16UnwrappedObject(Utf16JsonReader reader, JsonFieldTable direct } else { JsonCreatorFieldInfo field = creatorInfo.fields()[direct]; if (!field.skipNullRead(reader)) { - ((Object[]) rootWorkspace)[field.argumentIndex()] = field.readUtf16(reader); + field.readUtf16(reader, (Object[]) rootWorkspace); } } continue; @@ -1066,7 +1066,7 @@ private T readUtf8UnwrappedObject(Utf8JsonReader reader, JsonFieldTable directTa } else { JsonCreatorFieldInfo field = creatorInfo.fields()[direct]; if (!field.skipNullRead(reader)) { - ((Object[]) rootWorkspace)[field.argumentIndex()] = field.readUtf8(reader); + field.readUtf8(reader, (Object[]) rootWorkspace); } } continue; @@ -1133,7 +1133,7 @@ private void readLatin1Route( route.field().readLatin1(reader, workspace); } else { JsonCreatorFieldInfo field = route.creatorField(); - ((Object[]) workspace)[field.argumentIndex()] = field.readLatin1(reader); + field.readLatin1(reader, (Object[]) workspace); } } @@ -1151,7 +1151,7 @@ private void readUtf16Route( route.field().readUtf16(reader, workspace); } else { JsonCreatorFieldInfo field = route.creatorField(); - ((Object[]) workspace)[field.argumentIndex()] = field.readUtf16(reader); + field.readUtf16(reader, (Object[]) workspace); } } @@ -1169,7 +1169,7 @@ private void readUtf8Route( route.field().readUtf8(reader, workspace); } else { JsonCreatorFieldInfo field = route.creatorField(); - ((Object[]) workspace)[field.argumentIndex()] = field.readUtf8(reader); + field.readUtf8(reader, (Object[]) workspace); } } @@ -1449,7 +1449,7 @@ private Object[] readLatin1AnyCreatorArguments(Latin1JsonReader reader, JsonFiel markRead(seen, index, field.name()); } if (!field.skipNullRead(reader)) { - arguments[field.argumentIndex()] = field.readLatin1(reader); + field.readLatin1(reader, arguments); } } else { int match = table.match(hash); @@ -1506,7 +1506,7 @@ private Object[] readUtf16AnyCreatorArguments(Utf16JsonReader reader, JsonFieldT markRead(seen, index, field.name()); } if (!field.skipNullRead(reader)) { - arguments[field.argumentIndex()] = field.readUtf16(reader); + field.readUtf16(reader, arguments); } } else { int match = table.match(hash); @@ -1563,7 +1563,7 @@ private Object[] readUtf8AnyCreatorArguments(Utf8JsonReader reader, JsonFieldTab markRead(seen, index, field.name()); } if (!field.skipNullRead(reader)) { - arguments[field.argumentIndex()] = field.readUtf8(reader); + field.readUtf8(reader, arguments); } } else { int match = table.match(hash); @@ -1617,7 +1617,7 @@ private Object[] readLatin1CreatorArguments(Latin1JsonReader reader) { markRead(seen, index, field.name()); } if (!field.skipNullRead(reader)) { - arguments[field.argumentIndex()] = field.readLatin1(reader); + field.readLatin1(reader, arguments); } } } while (reader.consume(',')); @@ -1652,7 +1652,7 @@ private Object[] readUtf16CreatorArguments(Utf16JsonReader reader) { markRead(seen, index, field.name()); } if (!field.skipNullRead(reader)) { - arguments[field.argumentIndex()] = field.readUtf16(reader); + field.readUtf16(reader, arguments); } } } while (reader.consume(',')); @@ -1687,7 +1687,7 @@ private Object[] readUtf8CreatorArguments(Utf8JsonReader reader) { markRead(seen, index, field.name()); } if (!field.skipNullRead(reader)) { - arguments[field.argumentIndex()] = field.readUtf8(reader); + field.readUtf8(reader, arguments); } } } while (reader.consume(',')); diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ScalarCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ScalarCodecs.java index 548c8d113f..e597ed8543 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ScalarCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ScalarCodecs.java @@ -3454,6 +3454,9 @@ public AtomicReferenceArray readUtf16(Utf16JsonReader reader) { values[size++] = readElement(reader, codec); } while (reader.consumeNextCommaOrEndArray()); finishArray(reader, size); + if (onContentNullRead == NullHandling.SKIP) { + size = ArrayCodec.removeDecodedNulls(values, size); + } return new AtomicReferenceArray<>(Arrays.copyOf(values, size)); } @@ -3485,6 +3488,9 @@ public AtomicReferenceArray readUtf8(Utf8JsonReader reader) { values[size++] = readElement(reader, codec); } while (reader.consumeNextCommaOrEndArray()); finishArray(reader, size); + if (onContentNullRead == NullHandling.SKIP) { + size = ArrayCodec.removeDecodedNulls(values, size); + } return new AtomicReferenceArray<>(Arrays.copyOf(values, size)); } @@ -3512,6 +3518,9 @@ private AtomicReferenceArray readAtomicReferenceArray( values[size++] = readElement(reader, codec); } while (reader.consumeNextCommaOrEndArray()); finishArray(reader, size); + if (onContentNullRead == NullHandling.SKIP) { + size = ArrayCodec.removeDecodedNulls(values, size); + } return new AtomicReferenceArray<>(Arrays.copyOf(values, size)); } diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonReaderCodegen.java b/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonReaderCodegen.java index b4603eb654..e34f92b5c3 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonReaderCodegen.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonReaderCodegen.java @@ -21,6 +21,7 @@ import static org.apache.fory.codegen.ExpressionUtils.add; import static org.apache.fory.codegen.ExpressionUtils.inline; +import static org.apache.fory.codegen.ExpressionUtils.notNull; import java.lang.reflect.Constructor; import java.lang.reflect.Executable; @@ -31,6 +32,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.function.Function; import org.apache.fory.codegen.Code; import org.apache.fory.codegen.CodegenContext; import org.apache.fory.codegen.Expression; @@ -744,6 +746,7 @@ private Expression anyCreatorReadExpression( loop.add(expectExpr(':')); Expression.Switch.Case[] cases = new Expression.Switch.Case[fields.length]; for (int i = 0; i < fields.length; i++) { + int argumentIndex = fields[i].argumentIndex(); cases[i] = new Expression.Switch.Case( i, @@ -752,10 +755,11 @@ private Expression anyCreatorReadExpression( nullReadGuard( fields[i].onNullRead(), fields[i].name(), - assignCreatorArgument( - arguments, - fields[i].argumentIndex(), - readCreatorValue(builder, fields[i], i))), + assignCreatorValue( + builder, + fields[i], + i, + value -> assignCreatorArgument(arguments, argumentIndex, value))), new Expression.Break())); } loop.add( @@ -1047,6 +1051,7 @@ private Expression creatorReadLoop( loop.add(readCreatorFieldIndex(fieldIndex, fields)); Expression.Switch.Case[] cases = new Expression.Switch.Case[fields.length]; for (int i = 0; i < fields.length; i++) { + int argumentIndex = fields[i].argumentIndex(); cases[i] = new Expression.Switch.Case( i, @@ -1055,10 +1060,11 @@ private Expression creatorReadLoop( nullReadGuard( fields[i].onNullRead(), fields[i].name(), - assignCreatorArgument( - arguments, - fields[i].argumentIndex(), - readCreatorValue(builder, fields[i], i))), + assignCreatorValue( + builder, + fields[i], + i, + value -> assignCreatorArgument(arguments, argumentIndex, value))), new Expression.Break())); } loop.add( @@ -1101,8 +1107,11 @@ private Expression orderedCreatorRead( nullReadGuard( field.onNullRead(), field.name(), - assignCreatorArgument( - arguments, field.argumentIndex(), readCreatorValue(builder, field, i))); + assignCreatorValue( + builder, + field, + i, + value -> assignCreatorArgument(arguments, field.argumentIndex(), value))); next = new Expression.If( tryReadOrderedCreatorField(field.name()), @@ -1686,22 +1695,7 @@ private Expression readCreatorValue( return new Expression.Cast(constructCarrier(builder, transparent, value), TypeRef.of(type)); } if (!isDirectCreatorPrimitive(field)) { - Expression codec = - usesReaderSlot(field.typeInfo()) - ? readerFromSlot(fieldRef("r" + id, JsonTypeInfo.class)) - : fieldRef("r" + id, readerCapabilityType()); - Expression value = - new Expression.Invoke(codec, readMethod(), TypeRef.of(Object.class), readerRef()); - if (type.isPrimitive()) { - value = - new Expression.StaticInvoke( - JsonCreatorFieldInfo.class, - "requirePrimitive", - TypeRef.of(Object.class), - value, - Expression.Literal.ofClass(type)); - } - return new Expression.Cast(value, TypeRef.of(type)); + return creatorDecodedValue(field, readCreatorDecoded(field, id, false)); } if (type == boolean.class) { return readBooleanExpr(); @@ -1732,6 +1726,54 @@ private Expression readCreatorValue( throw new IllegalStateException("Unsupported primitive creator type " + type); } + /** + * Assigns one creator value. With SKIP, a null decoded by the selected codec leaves the argument + * absent, like an explicit JSON null; other modes emit the original assignment unchanged. + */ + private Expression assignCreatorValue( + JsonGeneratedCodecBuilder builder, + JsonCreatorFieldInfo field, + int id, + Function assign) { + if (field.onNullRead() != NullHandling.SKIP + || field.directUnboxedValueCodec() != null + || field.transparentUnboxedValueCodec() != null + || isDirectCreatorPrimitive(field)) { + return assign.apply(readCreatorValue(builder, field, id)); + } + Expression decoded = readCreatorDecoded(field, id, true); + return new Expression.If(notNull(decoded), assign.apply(creatorDecodedValue(field, decoded))); + } + + /** Reads the raw codec value; only the SKIP null test needs a nullable result local. */ + private Expression readCreatorDecoded(JsonCreatorFieldInfo field, int id, boolean nullable) { + Expression codec = + usesReaderSlot(field.typeInfo()) + ? readerFromSlot(fieldRef("r" + id, JsonTypeInfo.class)) + : fieldRef("r" + id, readerCapabilityType()); + return new Expression.Invoke( + codec, + readMethod(), + nullable ? "decoded" : "", + TypeRef.of(Object.class), + nullable, + readerRef()); + } + + private static Expression creatorDecodedValue(JsonCreatorFieldInfo field, Expression value) { + Class type = field.rawType(); + if (type.isPrimitive()) { + value = + new Expression.StaticInvoke( + JsonCreatorFieldInfo.class, + "requirePrimitive", + TypeRef.of(Object.class), + value, + Expression.Literal.ofClass(type)); + } + return new Expression.Cast(value, TypeRef.of(type)); + } + private Expression readCreatorTerminal( JsonGeneratedCodecBuilder builder, JsonCreatorFieldInfo field, int id) { return readTerminal(builder, field.typeInfo(), id, false, creatorReader(field, id)); @@ -2573,10 +2615,13 @@ private Expression unwrappedDirectCreator( nullReadGuard( field.onNullRead(), field.name(), - new Expression.AssignArrayElem( - root, - readCreatorValue(builder, field, i), - Expression.Literal.ofInt(field.argumentIndex()))), + assignCreatorValue( + builder, + field, + i, + value -> + new Expression.AssignArrayElem( + root, value, Expression.Literal.ofInt(field.argumentIndex())))), new Expression.Break())); } return new Expression.Switch(index, cases, new Expression.Invoke(readerRef(), "skipValue")); @@ -2650,10 +2695,15 @@ private Expression unwrappedRouteSwitch( } else { JsonCreatorFieldInfo field = route.creatorField(); read.add( - new Expression.AssignArrayElem( - new Expression.Cast(workspace, TypeRef.of(Object[].class)), - readCreatorValue(builder, field, id), - Expression.Literal.ofInt(field.argumentIndex()))); + assignCreatorValue( + builder, + field, + id, + value -> + new Expression.AssignArrayElem( + new Expression.Cast(workspace, TypeRef.of(Object[].class)), + value, + Expression.Literal.ofInt(field.argumentIndex())))); } NullHandling handling = route.field() == null ? route.creatorField().onNullRead() : route.field().onNullRead(); @@ -5159,7 +5209,21 @@ final Expression readAsciiEnumField( final Expression readResolvedField( JsonGeneratedCodecBuilder builder, JsonFieldInfo property, int id, Expression object) { - return builder.setField(property, object, readResolvedValue(property, id)); + if (property.onNullRead() != NullHandling.SKIP) { + return builder.setField(property, object, readResolvedValue(property, id)); + } + // SKIP leaves the property unchanged when the selected codec decodes null, like an explicit + // JSON null. The decoded value is a local so the null test does not repeat the codec call. + Expression decoded = + new Expression.Invoke( + propertyReader(property, id), + readObjectMethod(), + "decoded", + TypeRef.of(Object.class), + true, + readerRef()); + return new Expression.If( + notNull(decoded), builder.setField(property, object, resolvedValue(property, id, decoded))); } final Expression readCollection( @@ -5208,14 +5272,19 @@ final Expression readResolvedValue(JsonFieldInfo property, int id) { // The selected capability consumes the complete nullable value. Requesting expression // null-state here only emits dead boolean locals around codec calls and bloats hot generated // reader methods. - Expression value = + return resolvedValue( + property, + id, inline( new Expression.Invoke( propertyReader(property, id), readObjectMethod(), TypeRef.of(Object.class), false, - readerRef())); + readerRef()))); + } + + private Expression resolvedValue(JsonFieldInfo property, int id, Expression value) { if (property.readRawType().isPrimitive()) { value = new Expression.Invoke( diff --git a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java index 5dd14ef03e..bc86d91696 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java @@ -192,37 +192,52 @@ private JsonTypeInfo selectedTypeInfo(JsonTypeResolver resolver) { : resolver.getTypeInfo(typeRef, formatAnnotation); } - public Object readLatin1(Latin1JsonReader reader) { + /** Stores the decoded argument; SKIP leaves it absent when the selected codec decodes null. */ + public void readLatin1(Latin1JsonReader reader, Object[] arguments) { if (readOccurrenceNull(reader)) { - return null; + arguments[argumentIndex] = null; + return; } Object value = unboxedValueCodec == null ? typeInfo.latin1Reader().readLatin1(reader) : unboxedValueCodec.readLatin1Carrier(reader); - return requirePrimitive(value, rawType); + if (value == null && onNullRead == NullHandling.SKIP) { + return; + } + arguments[argumentIndex] = requirePrimitive(value, rawType); } - public Object readUtf16(Utf16JsonReader reader) { + /** Stores the decoded argument; SKIP leaves it absent when the selected codec decodes null. */ + public void readUtf16(Utf16JsonReader reader, Object[] arguments) { if (readOccurrenceNull(reader)) { - return null; + arguments[argumentIndex] = null; + return; } Object value = unboxedValueCodec == null ? typeInfo.utf16Reader().readUtf16(reader) : unboxedValueCodec.readUtf16Carrier(reader); - return requirePrimitive(value, rawType); + if (value == null && onNullRead == NullHandling.SKIP) { + return; + } + arguments[argumentIndex] = requirePrimitive(value, rawType); } - public Object readUtf8(Utf8JsonReader reader) { + /** Stores the decoded argument; SKIP leaves it absent when the selected codec decodes null. */ + public void readUtf8(Utf8JsonReader reader, Object[] arguments) { if (readOccurrenceNull(reader)) { - return null; + arguments[argumentIndex] = null; + return; } Object value = unboxedValueCodec == null ? typeInfo.utf8Reader().readUtf8(reader) : unboxedValueCodec.readUtf8Carrier(reader); - return requirePrimitive(value, rawType); + if (value == null && onNullRead == NullHandling.SKIP) { + return; + } + arguments[argumentIndex] = requirePrimitive(value, rawType); } private boolean readOccurrenceNull(org.apache.fory.json.reader.JsonReader reader) { diff --git a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java index 7b756e80bb..50818f39b3 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java @@ -577,6 +577,14 @@ public boolean skipNullRead(JsonReader reader) { return true; } + /** Assigns a decoded value; SKIP leaves the property unchanged when the codec decodes null. */ + private void putDecoded(Object object, Object value, boolean primitive) { + if (value == null && onNullRead == NullHandling.SKIP) { + return; + } + readAccessor.putObject(object, primitive ? requirePrimitive(value) : value); + } + /** Returns parent-local metadata with a transformed JSON name and the same Java member owner. */ public JsonFieldInfo withName(String transformedName, TypeRef ownerType) { JsonFieldInfo copy = @@ -1073,14 +1081,13 @@ public void readLatin1(Latin1JsonReader reader, Object object) { readAccessor.putChar(object, reader.readChar()); return; case KIND_CUSTOM_PRIMITIVE: - readAccessor.putObject( - object, requirePrimitive(readTypeInfo.latin1Reader().readLatin1(reader))); + putDecoded(object, readTypeInfo.latin1Reader().readLatin1(reader), true); return; case KIND_UNBOXED: putCarrier(object, readUnboxedLatin1(reader)); return; default: - readAccessor.putObject(object, readTypeInfo.latin1Reader().readLatin1(reader)); + putDecoded(object, readTypeInfo.latin1Reader().readLatin1(reader), false); } } @@ -1137,14 +1144,13 @@ public void readUtf16(Utf16JsonReader reader, Object object) { readAccessor.putChar(object, reader.readChar()); return; case KIND_CUSTOM_PRIMITIVE: - readAccessor.putObject( - object, requirePrimitive(readTypeInfo.utf16Reader().readUtf16(reader))); + putDecoded(object, readTypeInfo.utf16Reader().readUtf16(reader), true); return; case KIND_UNBOXED: putCarrier(object, readUnboxedUtf16(reader)); return; default: - readAccessor.putObject(object, readTypeInfo.utf16Reader().readUtf16(reader)); + putDecoded(object, readTypeInfo.utf16Reader().readUtf16(reader), false); } } @@ -1201,14 +1207,13 @@ public void readUtf8(Utf8JsonReader reader, Object object) { readAccessor.putChar(object, reader.readChar()); return; case KIND_CUSTOM_PRIMITIVE: - readAccessor.putObject( - object, requirePrimitive(readTypeInfo.utf8Reader().readUtf8(reader))); + putDecoded(object, readTypeInfo.utf8Reader().readUtf8(reader), true); return; case KIND_UNBOXED: putCarrier(object, readUnboxedUtf8(reader)); return; default: - readAccessor.putObject(object, readTypeInfo.utf8Reader().readUtf8(reader)); + putDecoded(object, readTypeInfo.utf8Reader().readUtf8(reader), false); } } diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonNullHandlingTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonNullHandlingTest.java index 46c0d63354..737fdb87ea 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonNullHandlingTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonNullHandlingTest.java @@ -94,7 +94,9 @@ public void propertyAssignments() { value = read(skip, "{\"value\":\"new\",\"value\":null}", Values.class, reader); assertEquals(value.value, "new"); assertEquals(value.calls, 1); - assertNull(read(skip, "{\"value\":\"decode-null\"}", Values.class, reader).value); + value = read(skip, "{\"value\":\"new\",\"value\":\"decode-null\"}", Values.class, reader); + assertEquals(value.value, "new"); + assertEquals(value.calls, 1); } assertNull(skip.fromJson("null", Values.class)); assertEquals(skip.fromJson("null", new TypeRef>() {}), Optional.empty()); @@ -102,6 +104,41 @@ public void propertyAssignments() { ForyJsonException.class, () -> newJson().fromJson("{\"count\":null}", Values.class)); } + @Test + public void decodedNullProperties() { + ForyJson set = newJson(); + ForyJson skip = newJsonBuilder().onNullRead(NullHandling.SKIP).build(); + ForyJson strict = + newJsonBuilder() + .onNullRead(NullHandling.SKIP) + .failOnMissingRequiredProperties(true) + .build(); + String text = "{\"field\":\"new\",\"field\":\"decode-null\",\"value\":\"decode-null\"}"; + for (int reader = 0; reader < 4; reader++) { + DecodedValues value = read(skip, text, DecodedValues.class, reader); + assertEquals(value.field, "new"); + assertEquals(value.value, "initial"); + assertEquals(value.calls, 0); + value = read(set, text, DecodedValues.class, reader); + assertNull(value.field); + assertNull(value.value); + assertEquals(value.calls, 1); + assertEquals( + read( + strict, + "{\"value\":\"new\",\"value\":\"decode-null\"}", + DecodedCreated.class, + reader) + .value, + "new"); + int representation = reader; + assertThrows( + ForyJsonException.class, + () -> read(strict, "{\"value\":\"decode-null\"}", DecodedCreated.class, representation)); + assertNull(read(set, "{\"value\":\"decode-null\"}", DecodedCreated.class, reader).value); + } + } + @Test public void creatorPresence() { ForyJson skip = newJsonBuilder().onNullRead(NullHandling.SKIP).build(); @@ -299,9 +336,23 @@ public void customChildAndInvalidTargets() { ForyJson json = newJsonBuilder().onContentNullRead(NullHandling.SKIP).build(); for (int reader = 0; reader < 4; reader++) { CustomContents value = - read(json, "{\"values\":[null,\"decode-null\",\"a\"]}", CustomContents.class, reader); - assertEquals(value.values, Arrays.asList(null, "a")); + read( + json, + "{\"values\":[null,\"decode-null\",\"a\"],\"set\":[\"decode-null\",\"b\"]," + + "\"array\":[\"decode-null\",\"c\"],\"atomic\":[\"e\",\"decode-null\"]," + + "\"map\":{\"x\":\"decode-null\",\"y\":\"d\"}}", + CustomContents.class, + reader); + assertEquals(value.values, ImmutableList.of("a")); + assertEquals(value.set, ImmutableSet.of("b")); + assertEquals(value.array, new String[] {"c"}); + assertEquals(value.atomic.length(), 1); + assertEquals(value.atomic.get(0), "e"); + assertEquals(value.map, ImmutableMap.of("y", "d")); } + CustomContents kept = + newJson().fromJson("{\"values\":[\"decode-null\",\"a\"]}", CustomContents.class); + assertEquals(kept.values, Arrays.asList(null, "a")); for (Class type : new Class[] { ScalarContent.class, @@ -317,6 +368,26 @@ public void customChildAndInvalidTargets() { json.fromJson("{\"values\":[null]}", OpaqueSet.class).values, Arrays.asList((String) null)); } + @Test + public void registeredElementCodec() { + ForyJson json = + newJsonBuilder() + .onContentNullRead(NullHandling.SKIP) + .registerCodec(Token.class, new TokenCodec()) + .build(); + String text = "{\"tokens\":[\"a\",\"decode-null\",\"b\",\"decode-null\"]}"; + for (int reader = 0; reader < 4; reader++) { + Tokens value = read(json, text, Tokens.class, reader); + assertEquals(value.tokens.size(), 2); + assertEquals(value.tokens.get(0).value, "a"); + assertEquals(value.tokens.get(1).value, "b"); + } + byte[] root = "[\"a\",\"decode-null\",\"b\"]".getBytes(StandardCharsets.UTF_8); + for (int i = 0; i < 3; i++) { + assertEquals(json.fromJson(root, new TypeRef>() {}).size(), 2); + } + } + @Test public void builderSnapshotsAndFailureCleanup() { ForyJsonBuilder builder = newJsonBuilder().onNullRead(NullHandling.SKIP); @@ -492,6 +563,45 @@ public Integer read(JsonReader reader) { public static class CustomContents { @JsonCodec(elementCodec = NullStringCodec.class) public List values; + + @JsonCodec(elementCodec = NullStringCodec.class) + public Set set; + + @JsonCodec(elementCodec = NullStringCodec.class) + public String[] array; + + @JsonCodec(elementCodec = NullStringCodec.class) + public AtomicReferenceArray atomic; + + @JsonCodec(valueCodec = NullStringCodec.class) + public Map map; + } + + public static class DecodedValues { + @JsonCodec(NullStringCodec.class) + public String field = "initial"; + + private String value = "initial"; + @JsonIgnore public int calls; + + public void setValue(String value) { + this.value = value; + calls++; + } + + @JsonCodec(NullStringCodec.class) + public String getValue() { + return value; + } + } + + public static class DecodedCreated { + public final String value; + + @JsonCreator + public DecodedCreated(@JsonProperty("value") @JsonCodec(NullStringCodec.class) String value) { + this.value = value; + } } public static class ScalarContent { @@ -538,6 +648,31 @@ public static class OpaqueSet { public List values; } + public static class Token { + public final String value; + + Token(String value) { + this.value = value; + } + } + + public static class Tokens { + public List tokens; + } + + public static class TokenCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, Token value) { + writer.writeString(value.value); + } + + @Override + public Token read(JsonReader reader) { + String value = reader.readString(); + return "decode-null".equals(value) ? null : new Token(value); + } + } + public static class NullStringCodec extends AbstractJsonValueCodec { @Override public void write(JsonWriter writer, String value) { From 1850d9a1c7c61bb9e7ce5a721a1d8f8781d85a46 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 15:57:38 +0100 Subject: [PATCH 2/4] fix(java): skip codec-decoded nulls for Any values and unwrapped groups Under content SKIP, a null decoded by an Any value codec is no longer put into the Any map or passed to the Any setter. Under property SKIP, an unwrapped child property (field or creator argument) is decoded before its group is created, so a decoded null does not publish an otherwise absent group. SET keeps the original group-then-read order. Also fix the read-side null handling guide, which still stated that codec nulls are never filtered. Co-Authored-By: Claude Opus 5.5 --- docs/json/annotations.md | 15 +- docs/json/custom-codecs.md | 3 +- .../org/apache/fory/json/ForyJsonBuilder.java | 4 +- .../fory/json/annotation/JsonProperty.java | 4 +- .../apache/fory/json/codec/ObjectCodec.java | 166 +++++++++++++++--- .../fory/json/codegen/JsonReaderCodegen.java | 108 ++++++++---- .../fory/json/meta/JsonCreatorFieldInfo.java | 63 +++++-- .../apache/fory/json/meta/JsonFieldInfo.java | 26 +++ .../fory/json/JsonNullHandlingTest.java | 83 +++++++++ 9 files changed, 384 insertions(+), 88 deletions(-) diff --git a/docs/json/annotations.md b/docs/json/annotations.md index 9a5303a2c2..27d4cf802b 100644 --- a/docs/json/annotations.md +++ b/docs/json/annotations.md @@ -234,15 +234,16 @@ Constructor parameters follow their existing missing-property defaults and requi checks. A skipped duplicate does not erase an earlier value: `{"seats":["a"],"seats":null}` keeps `"a"`. Constructor-bypassed objects have no initializer to preserve. +`SET` preserves codec behavior: null may become `Optional.empty()`, or fail for a primitive or +non-null Kotlin value. `SKIP` and `FAIL` handle a literal JSON null before that decoding; the string +`"null"` is an ordinary value. + `SKIP` also applies when a selected codec returns Java null for a non-null JSON value. For example, a trimming property codec that decodes `" "` to null leaves the current value unchanged, and a -trimming `elementCodec` omits that collection element. This covers property assignments, collection -and reference-array elements, and map values. `FAIL` still rejects only an explicit JSON null. - -`SET` preserves codec behavior: null may become `Optional.empty()`, or fail for a primitive or -non-null Kotlin value. `SKIP` and `FAIL` act before that decoding. Only the literal JSON null is -affected; the string `"null"` and a custom codec returning Java null for another token are not -filtered. These options do not affect writing or change the root value's null behavior. +trimming `elementCodec` omits that collection element. This covers property and creator +assignments, Any values, collection, reference-array and `AtomicReferenceArray` elements, and map +values. `SET` assigns such a null normally, and `FAIL` rejects only a literal JSON null. These +options do not affect writing or change the root value's null behavior. Content overrides are shallow. For `List>`, a property override skips null inner lists; elements inside retained lists follow the global setting. Map keys are unaffected, and a diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index 04cbcbb0f1..f4b31439aa 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -132,7 +132,8 @@ applicable read setting is `SET`. Property `onNullRead` and Fory container `onContentNullRead` settings intercept literal null before invoking a selected child codec when configured as `SKIP` or `FAIL`. Under `SKIP`, a Java null returned after consuming a non-null token is also omitted: the property keeps its current value, and the -collection element, reference-array element, or map value is not inserted. `SET` and `FAIL` assign +collection element, reference-array or `AtomicReferenceArray` element, map value, or Any value is +not inserted. `SET` and `FAIL` assign such a value normally. The registered instance is shared across concurrent operations and must be thread-safe. diff --git a/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java b/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java index 1ab3f72059..b075df9e0c 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/ForyJsonBuilder.java @@ -142,8 +142,8 @@ public ForyJsonBuilder onNullRead(NullHandling handling) { * including root containers. Defaults to {@code SET}. Property {@link * org.apache.fory.json.annotation.JsonProperty#onContentNullRead()} overrides the immediate * container's setting. {@code SKIP} also omits a Java null returned by a child codec for a - * collection or reference-array element or a map value. Complete custom codecs retain their - * representation. Writing is unaffected. + * collection, reference-array, or AtomicReferenceArray element, a map value, or an Any value. + * Complete custom codecs retain their representation. Writing is unaffected. * * @throws IllegalArgumentException if handling is {@code DEFAULT} * @throws NullPointerException if handling is null diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonProperty.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonProperty.java index aef29ad8f6..337c68d804 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonProperty.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonProperty.java @@ -99,8 +99,8 @@ * their own settings. Explicit {@code SKIP} and {@code FAIL} require a container representation * owned by Fory; explicit {@code SET} also accepts a complete custom container codec. Encoded * binary strings and non-container targets reject explicit settings. {@code SKIP} also omits a - * Java null returned by the child codec of a collection, reference array, or map value for a - * non-null JSON token; {@code FAIL} rejects only explicit JSON null. + * Java null returned by the child codec of a collection, reference array, AtomicReferenceArray, + * or map value for a non-null JSON token; {@code FAIL} rejects only explicit JSON null. */ NullHandling onContentNullRead() default NullHandling.DEFAULT; diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java index f7529b7799..4d4efebcf0 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java @@ -930,10 +930,17 @@ private T readLatin1UnwrappedObject(Latin1JsonReader reader, JsonFieldTable dire } String name = reader.materializeFieldName(start); if (creatorInfo == null && !anyInfo.fieldRead()) { - anyInfo.put(rootWorkspace, name, anyReader.readLatin1(reader)); + Object value = anyReader.readLatin1(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } + anyInfo.put(rootWorkspace, name, value); } else { reserveAnyEntry(reader); Object value = anyReader.readLatin1(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } if (anyMap == null) { if (creatorInfo == null) { anyMap = anyInfo.readMap(rootWorkspace); @@ -1010,10 +1017,17 @@ private T readUtf16UnwrappedObject(Utf16JsonReader reader, JsonFieldTable direct } String name = reader.materializeFieldName(start); if (creatorInfo == null && !anyInfo.fieldRead()) { - anyInfo.put(rootWorkspace, name, anyReader.readUtf16(reader)); + Object value = anyReader.readUtf16(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } + anyInfo.put(rootWorkspace, name, value); } else { reserveAnyEntry(reader); Object value = anyReader.readUtf16(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } if (anyMap == null) { if (creatorInfo == null) { anyMap = anyInfo.readMap(rootWorkspace); @@ -1090,10 +1104,17 @@ private T readUtf8UnwrappedObject(Utf8JsonReader reader, JsonFieldTable directTa } String name = reader.materializeFieldName(start); if (creatorInfo == null && !anyInfo.fieldRead()) { - anyInfo.put(rootWorkspace, name, anyReader.readUtf8(reader)); + Object value = anyReader.readUtf8(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } + anyInfo.put(rootWorkspace, name, value); } else { reserveAnyEntry(reader); Object value = anyReader.readUtf8(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } if (anyMap == null) { if (creatorInfo == null) { anyMap = anyInfo.readMap(rootWorkspace); @@ -1127,14 +1148,33 @@ private void readLatin1Route( : route.creatorField().skipNullRead(reader)) { return; } - Object workspace = ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present); - ObjectCodec child = route.group().childCodec(); - if (child.creatorInfo == null) { - route.field().readLatin1(reader, workspace); - } else { - JsonCreatorFieldInfo field = route.creatorField(); - field.readLatin1(reader, (Object[]) workspace); + JsonFieldInfo field = route.field(); + if (field != null) { + if (field.decodesBeforeGroup()) { + Object value = field.decodeLatin1(reader); + if (value != null) { + field.putDecoded( + ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present), value); + } + return; + } + field.readLatin1( + reader, ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present)); + return; } + JsonCreatorFieldInfo creatorField = route.creatorField(); + if (creatorField.onNullRead() == NullHandling.SKIP) { + // Decode first: a null decoded by the codec must not publish an otherwise absent group. + Object value = creatorField.readLatin1Value(reader); + if (value != null) { + Object[] arguments = + (Object[]) ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present); + arguments[creatorField.argumentIndex()] = value; + } + return; + } + creatorField.readLatin1( + reader, (Object[]) ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present)); } private void readUtf16Route( @@ -1145,14 +1185,33 @@ private void readUtf16Route( : route.creatorField().skipNullRead(reader)) { return; } - Object workspace = ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present); - ObjectCodec child = route.group().childCodec(); - if (child.creatorInfo == null) { - route.field().readUtf16(reader, workspace); - } else { - JsonCreatorFieldInfo field = route.creatorField(); - field.readUtf16(reader, (Object[]) workspace); + JsonFieldInfo field = route.field(); + if (field != null) { + if (field.decodesBeforeGroup()) { + Object value = field.decodeUtf16(reader); + if (value != null) { + field.putDecoded( + ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present), value); + } + return; + } + field.readUtf16( + reader, ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present)); + return; + } + JsonCreatorFieldInfo creatorField = route.creatorField(); + if (creatorField.onNullRead() == NullHandling.SKIP) { + // Decode first: a null decoded by the codec must not publish an otherwise absent group. + Object value = creatorField.readUtf16Value(reader); + if (value != null) { + Object[] arguments = + (Object[]) ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present); + arguments[creatorField.argumentIndex()] = value; + } + return; } + creatorField.readUtf16( + reader, (Object[]) ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present)); } private void readUtf8Route( @@ -1163,14 +1222,32 @@ private void readUtf8Route( : route.creatorField().skipNullRead(reader)) { return; } - Object workspace = ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present); - ObjectCodec child = route.group().childCodec(); - if (child.creatorInfo == null) { - route.field().readUtf8(reader, workspace); - } else { - JsonCreatorFieldInfo field = route.creatorField(); - field.readUtf8(reader, (Object[]) workspace); + JsonFieldInfo field = route.field(); + if (field != null) { + if (field.decodesBeforeGroup()) { + Object value = field.decodeUtf8(reader); + if (value != null) { + field.putDecoded( + ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present), value); + } + return; + } + field.readUtf8(reader, ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present)); + return; + } + JsonCreatorFieldInfo creatorField = route.creatorField(); + if (creatorField.onNullRead() == NullHandling.SKIP) { + // Decode first: a null decoded by the codec must not publish an otherwise absent group. + Object value = creatorField.readUtf8Value(reader); + if (value != null) { + Object[] arguments = + (Object[]) ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present); + arguments[creatorField.argumentIndex()] = value; + } + return; } + creatorField.readUtf8( + reader, (Object[]) ensureUnwrappedGroup(reader, route.group(), groupWorkspaces, present)); } private void finishUnwrappedAny( @@ -1272,6 +1349,9 @@ && tryReadLatin1Field(reader, readFields[expectedIndex])) { if (anyInfo.fieldRead()) { reserveAnyEntry(reader); Object value = anyReader.readLatin1(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } if (anyMap == null) { anyMap = anyInfo.readMap(object); if (anyMap == null) { @@ -1284,7 +1364,11 @@ && tryReadLatin1Field(reader, readFields[expectedIndex])) { } putAnyMap(anyMap, name, value); } else { - anyInfo.put(object, name, anyReader.readLatin1(reader)); + Object value = anyReader.readLatin1(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } + anyInfo.put(object, name, value); } } } while (reader.consume(',')); @@ -1334,6 +1418,9 @@ && tryReadUtf16Field(reader, readFields[expectedIndex])) { if (anyInfo.fieldRead()) { reserveAnyEntry(reader); Object value = anyReader.readUtf16(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } if (anyMap == null) { anyMap = anyInfo.readMap(object); if (anyMap == null) { @@ -1346,7 +1433,11 @@ && tryReadUtf16Field(reader, readFields[expectedIndex])) { } putAnyMap(anyMap, name, value); } else { - anyInfo.put(object, name, anyReader.readUtf16(reader)); + Object value = anyReader.readUtf16(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } + anyInfo.put(object, name, value); } } } while (reader.consume(',')); @@ -1396,6 +1487,9 @@ && tryReadUtf8Field(reader, readFields[expectedIndex])) { if (anyInfo.fieldRead()) { reserveAnyEntry(reader); Object value = anyReader.readUtf8(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } if (anyMap == null) { anyMap = anyInfo.readMap(object); if (anyMap == null) { @@ -1408,7 +1502,11 @@ && tryReadUtf8Field(reader, readFields[expectedIndex])) { } putAnyMap(anyMap, name, value); } else { - anyInfo.put(object, name, anyReader.readUtf8(reader)); + Object value = anyReader.readUtf8(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } + anyInfo.put(object, name, value); } } } while (reader.consume(',')); @@ -1462,6 +1560,9 @@ private Object[] readLatin1AnyCreatorArguments(Latin1JsonReader reader, JsonFiel String name = reader.materializeFieldName(start); reserveAnyEntry(reader); Object value = anyReader.readLatin1(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } if (anyMap == null) { anyMap = newAnyMap(reader); } @@ -1519,6 +1620,9 @@ private Object[] readUtf16AnyCreatorArguments(Utf16JsonReader reader, JsonFieldT String name = reader.materializeFieldName(start); reserveAnyEntry(reader); Object value = anyReader.readUtf16(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } if (anyMap == null) { anyMap = newAnyMap(reader); } @@ -1576,6 +1680,9 @@ private Object[] readUtf8AnyCreatorArguments(Utf8JsonReader reader, JsonFieldTab String name = reader.materializeFieldName(start); reserveAnyEntry(reader); Object value = anyReader.readUtf8(reader); + if (anyInfo.skipDecodedNull(value)) { + continue; + } if (anyMap == null) { anyMap = newAnyMap(reader); } @@ -2189,6 +2296,11 @@ private void resolveTypes(JsonTypeResolver resolver) { } } + /** Returns whether content SKIP omits an Any value that its codec decoded to null. */ + public boolean skipDecodedNull(Object value) { + return value == null && onContentNullRead == NullHandling.SKIP; + } + private boolean skipNullRead(JsonReader reader) { if (onContentNullRead == NullHandling.SET || !reader.tryReadNullToken()) { return false; diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonReaderCodegen.java b/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonReaderCodegen.java index e34f92b5c3..00681fdeb6 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonReaderCodegen.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codegen/JsonReaderCodegen.java @@ -805,11 +805,7 @@ private Expression readUnknownCreator(Expression fieldStart, Expression hash, Ex new Expression.Invoke( readerRef(), "materializeFieldName", TypeRef.of(String.class), fieldStart) .inline()); - Expression value = - new Expression.Variable( - "anyValue", - new Expression.Invoke( - anyReaderRef(), readMethod(), TypeRef.of(Object.class), readerRef())); + Expression value = anyValue(); Expression create = new Expression.Assign( anyMap, @@ -821,9 +817,12 @@ private Expression readUnknownCreator(Expression fieldStart, Expression hash, Ex name, new Expression.Invoke(ownerRef(), "reserveAnyEntry", readerRef()), value, - new Expression.If( - eq(anyMap, new Expression.Null(TypeRef.of(Map.class), false)), create), - new Expression.Invoke(ownerRef(), "putAnyMap", anyMap, name, value)); + skipDecodedAnyNull( + value, + new Expression.ListExpression( + new Expression.If( + eq(anyMap, new Expression.Null(TypeRef.of(Map.class), false)), create), + new Expression.Invoke(ownerRef(), "putAnyMap", anyMap, name, value)))); return new Expression.ListExpression( match, new Expression.If( @@ -2680,7 +2679,10 @@ private Expression unwrappedRouteSwitch( ReadRoute route = routes[i]; int id = directCount + i; Expression.ListExpression read = new Expression.ListExpression(); - addEnsureUnwrappedGroup(read, route.group(), workspaces, present); + // Under SKIP, a null decoded by the codec must not publish an otherwise absent group, so the + // group is ensured only on the assignment branch of a decoded value. + Expression.ListExpression ensure = new Expression.ListExpression(); + addEnsureUnwrappedGroup(ensure, route.group(), workspaces, present); int groupIndex = route.group().readIndex(); ObjectCodec child = route.group().childCodec(); Expression workspace = @@ -2691,7 +2693,17 @@ private Expression unwrappedRouteSwitch( throw new IllegalStateException("Creator group route must use creator metadata"); } Expression object = new Expression.Cast(workspace, TypeRef.of(child.type())); - read.add(readField(builder, ownerType, field, id, object, false)); + if (field.onNullRead() == NullHandling.SKIP && readsResolvedValue(field)) { + Expression decoded = readDecodedValue(field, id); + read.add( + new Expression.If( + notNull(decoded), + new Expression.ListExpression( + ensure, builder.setField(field, object, resolvedValue(field, id, decoded))))); + } else { + read.add(ensure); + read.add(readField(builder, ownerType, field, id, object, false)); + } } else { JsonCreatorFieldInfo field = route.creatorField(); read.add( @@ -2700,10 +2712,12 @@ private Expression unwrappedRouteSwitch( field, id, value -> - new Expression.AssignArrayElem( - new Expression.Cast(workspace, TypeRef.of(Object[].class)), - value, - Expression.Literal.ofInt(field.argumentIndex())))); + new Expression.ListExpression( + ensure, + new Expression.AssignArrayElem( + new Expression.Cast(workspace, TypeRef.of(Object[].class)), + value, + Expression.Literal.ofInt(field.argumentIndex()))))); } NullHandling handling = route.field() == null ? route.creatorField().onNullRead() : route.field().onNullRead(); @@ -4112,11 +4126,7 @@ private Expression readUnknown( new Expression.Invoke( readerRef(), "materializeFieldName", TypeRef.of(String.class), fieldStart) .inline()); - Expression value = - new Expression.Variable( - "anyValue", - new Expression.Invoke( - anyReaderRef(), readMethod(), TypeRef.of(Object.class), readerRef())); + Expression value = anyValue(); Expression read; if (any.readSetter() != null) { Expression write = @@ -4130,7 +4140,7 @@ private Expression readUnknown( object, name, value); - read = new Expression.ListExpression(name, value, write); + read = new Expression.ListExpression(name, value, skipDecodedAnyNull(value, write)); } else { Reference map = new Reference("anyMap", TypeRef.of(Map.class)); Expression create = @@ -4172,7 +4182,7 @@ private Expression readUnknown( name, new Expression.Invoke(ownerRef(), "reserveAnyEntry", readerRef()), value, - write); + skipDecodedAnyNull(value, write)); } return new Expression.If( reserved, @@ -4183,6 +4193,22 @@ private Expression readUnknown( skip)); } + /** Reads one Any value; content SKIP needs a nullable local for the decoded-null test. */ + private Expression anyValue() { + boolean skip = resolver.sharedRegistry().onContentNullRead() == NullHandling.SKIP; + return new Expression.Variable( + "anyValue", + new Expression.Invoke( + anyReaderRef(), readMethod(), "", TypeRef.of(Object.class), skip, readerRef())); + } + + /** Under content SKIP, a null decoded by the Any value codec is omitted like a JSON null. */ + private Expression skipDecodedAnyNull(Expression value, Expression write) { + return resolver.sharedRegistry().onContentNullRead() == NullHandling.SKIP + ? new Expression.If(notNull(value), write) + : write; + } + private Expression updateExpectedIndex(Expression expectedIndex, Expression fieldIndex) { return new Expression.If( ge(fieldIndex, Expression.Literal.ofInt(0)), @@ -5214,14 +5240,7 @@ final Expression readResolvedField( } // SKIP leaves the property unchanged when the selected codec decodes null, like an explicit // JSON null. The decoded value is a local so the null test does not repeat the codec call. - Expression decoded = - new Expression.Invoke( - propertyReader(property, id), - readObjectMethod(), - "decoded", - TypeRef.of(Object.class), - true, - readerRef()); + Expression decoded = readDecodedValue(property, id); return new Expression.If( notNull(decoded), builder.setField(property, object, resolvedValue(property, id, decoded))); } @@ -5237,13 +5256,40 @@ final Expression readObject( JsonFieldInfo property, int id, Expression object) { - if (property.readRawType() == Object.class - || resolver.canonicalObjectCodec(property.readTypeInfo()) == null) { + if (readsResolvedValue(property)) { return readResolvedField(builder, property, id, object); } return builder.setField(property, object, readObjectValue(type, property, id)); } + /** Returns whether a property value is read through its selected codec by readResolvedField. */ + private boolean readsResolvedValue(JsonFieldInfo property) { + if (property.readsUnboxedValue()) { + return false; + } + switch (property.readKind()) { + case ARRAY: + case MAP: + return true; + case OBJECT: + return property.readRawType() == Object.class + || resolver.canonicalObjectCodec(property.readTypeInfo()) == null; + default: + return false; + } + } + + /** Reads the raw codec value into a nullable local for the SKIP decoded-null test. */ + private Expression readDecodedValue(JsonFieldInfo property, int id) { + return new Expression.Invoke( + propertyReader(property, id), + readObjectMethod(), + "decoded", + TypeRef.of(Object.class), + true, + readerRef()); + } + final Expression box(Class boxedType, Expression value) { return new Expression.StaticInvoke( boxedType, "valueOf", "", TypeRef.of(boxedType), false, true, false, value); diff --git a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java index bc86d91696..3466208aeb 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java @@ -194,50 +194,77 @@ private JsonTypeInfo selectedTypeInfo(JsonTypeResolver resolver) { /** Stores the decoded argument; SKIP leaves it absent when the selected codec decodes null. */ public void readLatin1(Latin1JsonReader reader, Object[] arguments) { + Object value = readLatin1Value(reader); + if (value != null || onNullRead != NullHandling.SKIP) { + arguments[argumentIndex] = value; + } + } + + /** + * Decodes one argument value. Under SKIP, callers have already consumed an explicit JSON null, so + * a null result means the selected codec decoded null and the argument stays absent. + */ + public Object readLatin1Value(Latin1JsonReader reader) { if (readOccurrenceNull(reader)) { - arguments[argumentIndex] = null; - return; + return null; } Object value = unboxedValueCodec == null ? typeInfo.latin1Reader().readLatin1(reader) : unboxedValueCodec.readLatin1Carrier(reader); - if (value == null && onNullRead == NullHandling.SKIP) { - return; - } - arguments[argumentIndex] = requirePrimitive(value, rawType); + return value == null && onNullRead == NullHandling.SKIP + ? null + : requirePrimitive(value, rawType); } /** Stores the decoded argument; SKIP leaves it absent when the selected codec decodes null. */ public void readUtf16(Utf16JsonReader reader, Object[] arguments) { + Object value = readUtf16Value(reader); + if (value != null || onNullRead != NullHandling.SKIP) { + arguments[argumentIndex] = value; + } + } + + /** + * Decodes one argument value. Under SKIP, callers have already consumed an explicit JSON null, so + * a null result means the selected codec decoded null and the argument stays absent. + */ + public Object readUtf16Value(Utf16JsonReader reader) { if (readOccurrenceNull(reader)) { - arguments[argumentIndex] = null; - return; + return null; } Object value = unboxedValueCodec == null ? typeInfo.utf16Reader().readUtf16(reader) : unboxedValueCodec.readUtf16Carrier(reader); - if (value == null && onNullRead == NullHandling.SKIP) { - return; - } - arguments[argumentIndex] = requirePrimitive(value, rawType); + return value == null && onNullRead == NullHandling.SKIP + ? null + : requirePrimitive(value, rawType); } /** Stores the decoded argument; SKIP leaves it absent when the selected codec decodes null. */ public void readUtf8(Utf8JsonReader reader, Object[] arguments) { + Object value = readUtf8Value(reader); + if (value != null || onNullRead != NullHandling.SKIP) { + arguments[argumentIndex] = value; + } + } + + /** + * Decodes one argument value. Under SKIP, callers have already consumed an explicit JSON null, so + * a null result means the selected codec decoded null and the argument stays absent. + */ + public Object readUtf8Value(Utf8JsonReader reader) { if (readOccurrenceNull(reader)) { - arguments[argumentIndex] = null; - return; + return null; } Object value = unboxedValueCodec == null ? typeInfo.utf8Reader().readUtf8(reader) : unboxedValueCodec.readUtf8Carrier(reader); - if (value == null && onNullRead == NullHandling.SKIP) { - return; - } - arguments[argumentIndex] = requirePrimitive(value, rawType); + return value == null && onNullRead == NullHandling.SKIP + ? null + : requirePrimitive(value, rawType); } private boolean readOccurrenceNull(org.apache.fory.json.reader.JsonReader reader) { diff --git a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java index 50818f39b3..7bb887c167 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java @@ -577,6 +577,15 @@ public boolean skipNullRead(JsonReader reader) { return true; } + /** + * Returns whether an unwrapped route must decode this property before creating its group. Under + * SKIP, a null decoded by the selected codec must not publish an otherwise absent group. + */ + public boolean decodesBeforeGroup() { + return onNullRead == NullHandling.SKIP + && (readPrimitiveKindId == 0 || readPrimitiveKindId == KIND_CUSTOM_PRIMITIVE); + } + /** Assigns a decoded value; SKIP leaves the property unchanged when the codec decodes null. */ private void putDecoded(Object object, Object value, boolean primitive) { if (value == null && onNullRead == NullHandling.SKIP) { @@ -585,6 +594,23 @@ private void putDecoded(Object object, Object value, boolean primitive) { readAccessor.putObject(object, primitive ? requirePrimitive(value) : value); } + /** Assigns a non-null value decoded by {@link #decodeLatin1} or its UTF-16/UTF-8 variants. */ + public void putDecoded(Object object, Object value) { + putDecoded(object, value, readPrimitiveKindId == KIND_CUSTOM_PRIMITIVE); + } + + public Object decodeLatin1(Latin1JsonReader reader) { + return readTypeInfo.latin1Reader().readLatin1(reader); + } + + public Object decodeUtf16(Utf16JsonReader reader) { + return readTypeInfo.utf16Reader().readUtf16(reader); + } + + public Object decodeUtf8(Utf8JsonReader reader) { + return readTypeInfo.utf8Reader().readUtf8(reader); + } + /** Returns parent-local metadata with a transformed JSON name and the same Java member owner. */ public JsonFieldInfo withName(String transformedName, TypeRef ownerType) { JsonFieldInfo copy = diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonNullHandlingTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonNullHandlingTest.java index 737fdb87ea..411d1b7896 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonNullHandlingTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonNullHandlingTest.java @@ -139,6 +139,48 @@ public void decodedNullProperties() { } } + @Test + public void decodedNullUnwrappedAndAny() { + ForyJson skip = + newJsonBuilder().onNullRead(NullHandling.SKIP).onContentNullRead(NullHandling.SKIP).build(); + ForyJson strict = + newJsonBuilder() + .onNullRead(NullHandling.SKIP) + .failOnMissingRequiredProperties(true) + .build(); + for (int reader = 0; reader < 4; reader++) { + assertNull(read(skip, "{\"value\":\"decode-null\"}", DecodedUnwrapped.class, reader).child); + assertEquals( + read(skip, "{\"value\":\"ok\",\"value\":\"decode-null\"}", DecodedUnwrapped.class, reader) + .child + .value, + "ok"); + assertNull( + read(strict, "{\"value\":\"decode-null\"}", DecodedCreatedUnwrapped.class, reader).child); + assertEquals( + read(strict, "{\"value\":\"ok\"}", DecodedCreatedUnwrapped.class, reader).child.value, + "ok"); + DecodedAnyValues value = + read(skip, "{\"x\":\"decode-null\",\"y\":\"a\"}", DecodedAnyValues.class, reader); + assertEquals(value.calls, reader == 1 ? 2 : 1); + assertFalse(value.sawNull); + DecodedAnyMap map = read(skip, "{\"x\":\"decode-null\"}", DecodedAnyMap.class, reader); + if (reader == 1) { + assertFalse(map.values.containsKey("x")); + } else { + assertNull(map.values); + } + DecodedCreatedAny created = + read( + skip, + "{\"x\":\"a\",\"x\":\"decode-null\",\"y\":\"decode-null\"}", + DecodedCreatedAny.class, + reader); + assertEquals(created.values.get("x"), "a"); + assertFalse(created.values.containsKey("y")); + } + } + @Test public void creatorPresence() { ForyJson skip = newJsonBuilder().onNullRead(NullHandling.SKIP).build(); @@ -595,6 +637,47 @@ public String getValue() { } } + public static class DecodedChild { + @JsonCodec(NullStringCodec.class) + public String value; + } + + public static class DecodedUnwrapped { + @JsonUnwrapped public DecodedChild child; + } + + public static class DecodedCreatedUnwrapped { + @JsonUnwrapped public DecodedCreated child; + } + + public static class DecodedAnyValues { + @JsonIgnore public int calls; + @JsonIgnore public boolean sawNull; + + @JsonAnySetter + public void accept(String name, @JsonCodec(NullStringCodec.class) String value) { + calls++; + sawNull |= value == null; + } + } + + public static class DecodedAnyMap { + @JsonAnyProperty + @JsonCodec(valueCodec = NullStringCodec.class) + public Map values; + } + + public static class DecodedCreatedAny { + @JsonAnyProperty + @JsonCodec(valueCodec = NullStringCodec.class) + public final Map values; + + @JsonCreator({"values"}) + public DecodedCreatedAny(Map values) { + this.values = values; + } + } + public static class DecodedCreated { public final String value; From 80b42ed2625c188d769ec4d52847b2d2ebb9314a Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 16:07:53 +0100 Subject: [PATCH 3/4] test(java): pin SET and FAIL keeping codec-decoded nulls Co-Authored-By: Claude Opus 5.5 --- .../fory/json/JsonNullHandlingTest.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonNullHandlingTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonNullHandlingTest.java index 411d1b7896..c1380044e9 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonNullHandlingTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonNullHandlingTest.java @@ -21,8 +21,10 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertThrows; +import static org.testng.Assert.assertTrue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -31,6 +33,7 @@ import java.lang.reflect.Array; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; @@ -181,6 +184,35 @@ public void decodedNullUnwrappedAndAny() { } } + @Test + public void decodedNullOutsideSkip() { + String contents = + "{\"values\":[\"decode-null\",\"a\"],\"set\":[\"decode-null\"]," + + "\"array\":[\"decode-null\"],\"atomic\":[\"decode-null\"]," + + "\"map\":{\"x\":\"decode-null\"}}"; + for (NullHandling handling : new NullHandling[] {NullHandling.SET, NullHandling.FAIL}) { + ForyJson json = newJsonBuilder().onNullRead(handling).onContentNullRead(handling).build(); + for (int reader = 0; reader < 4; reader++) { + CustomContents value = read(json, contents, CustomContents.class, reader); + assertEquals(value.values, Arrays.asList(null, "a")); + assertEquals(value.set, Collections.singleton(null)); + assertEquals(value.array, new String[] {null}); + assertEquals(value.atomic.length(), 1); + assertNull(value.atomic.get(0)); + assertEquals(value.map, Collections.singletonMap("x", null)); + DecodedValues values = + read(json, "{\"field\":\"decode-null\"}", DecodedValues.class, reader); + assertNull(values.field); + DecodedAnyMap map = read(json, "{\"x\":\"decode-null\"}", DecodedAnyMap.class, reader); + assertTrue(map.values.containsKey("x")); + assertNull(map.values.get("x")); + assertTrue(read(json, "{\"x\":\"decode-null\"}", DecodedAnyValues.class, reader).sawNull); + assertNotNull( + read(json, "{\"value\":\"decode-null\"}", DecodedUnwrapped.class, reader).child); + } + } + } + @Test public void creatorPresence() { ForyJson skip = newJsonBuilder().onNullRead(NullHandling.SKIP).build(); From 193d2b8486041dde36e01e2494189cbac8ca457c Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 16:20:35 +0100 Subject: [PATCH 4/4] fix(java): store unboxed creator carriers as decoded under SKIP Interpreted creator reads filtered a null unboxed carrier under SKIP, while generated readers and property paths store carriers as decoded. Keep the decoded-null skip to the selected codec value only. Co-Authored-By: Claude Opus 5.5 --- .../apache/fory/json/codec/ObjectCodec.java | 6 +- .../fory/json/meta/JsonCreatorFieldInfo.java | 110 +++++++++++------- 2 files changed, 68 insertions(+), 48 deletions(-) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java index 4d4efebcf0..357c0a7ce3 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodec.java @@ -1163,7 +1163,7 @@ private void readLatin1Route( return; } JsonCreatorFieldInfo creatorField = route.creatorField(); - if (creatorField.onNullRead() == NullHandling.SKIP) { + if (creatorField.decodesBeforeGroup()) { // Decode first: a null decoded by the codec must not publish an otherwise absent group. Object value = creatorField.readLatin1Value(reader); if (value != null) { @@ -1200,7 +1200,7 @@ private void readUtf16Route( return; } JsonCreatorFieldInfo creatorField = route.creatorField(); - if (creatorField.onNullRead() == NullHandling.SKIP) { + if (creatorField.decodesBeforeGroup()) { // Decode first: a null decoded by the codec must not publish an otherwise absent group. Object value = creatorField.readUtf16Value(reader); if (value != null) { @@ -1236,7 +1236,7 @@ private void readUtf8Route( return; } JsonCreatorFieldInfo creatorField = route.creatorField(); - if (creatorField.onNullRead() == NullHandling.SKIP) { + if (creatorField.decodesBeforeGroup()) { // Decode first: a null decoded by the codec must not publish an otherwise absent group. Object value = creatorField.readUtf8Value(reader); if (value != null) { diff --git a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java index 3466208aeb..0b3c8ed548 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java @@ -104,6 +104,14 @@ public boolean skipNullRead(JsonReader reader) { return true; } + /** + * Returns whether an unwrapped route must decode this argument before creating its group. Under + * SKIP, a null decoded by the selected codec must not publish an otherwise absent group. + */ + public boolean decodesBeforeGroup() { + return onNullRead == NullHandling.SKIP && unboxedValueCodec == null; + } + /** Returns parent-local metadata with a transformed JSON name and the same creator argument. */ public JsonCreatorFieldInfo withName(String transformedName) { return new JsonCreatorFieldInfo( @@ -192,79 +200,91 @@ private JsonTypeInfo selectedTypeInfo(JsonTypeResolver resolver) { : resolver.getTypeInfo(typeRef, formatAnnotation); } - /** Stores the decoded argument; SKIP leaves it absent when the selected codec decodes null. */ + /** + * Stores the decoded argument. SKIP leaves it absent when the selected codec decodes null; + * unboxed carriers are stored as decoded, like generated readers and property paths. + */ public void readLatin1(Latin1JsonReader reader, Object[] arguments) { - Object value = readLatin1Value(reader); + if (readOccurrenceNull(reader)) { + arguments[argumentIndex] = null; + return; + } + if (unboxedValueCodec != null) { + arguments[argumentIndex] = + requirePrimitive(unboxedValueCodec.readLatin1Carrier(reader), rawType); + return; + } + Object value = typeInfo.latin1Reader().readLatin1(reader); if (value != null || onNullRead != NullHandling.SKIP) { - arguments[argumentIndex] = value; + arguments[argumentIndex] = requirePrimitive(value, rawType); } } /** - * Decodes one argument value. Under SKIP, callers have already consumed an explicit JSON null, so - * a null result means the selected codec decoded null and the argument stays absent. + * Decodes a SKIP argument through its codec before an unwrapped group exists. The caller has + * already consumed an explicit JSON null, so null means the argument stays absent. */ public Object readLatin1Value(Latin1JsonReader reader) { - if (readOccurrenceNull(reader)) { - return null; - } - Object value = - unboxedValueCodec == null - ? typeInfo.latin1Reader().readLatin1(reader) - : unboxedValueCodec.readLatin1Carrier(reader); - return value == null && onNullRead == NullHandling.SKIP - ? null - : requirePrimitive(value, rawType); + Object value = typeInfo.latin1Reader().readLatin1(reader); + return value == null ? null : requirePrimitive(value, rawType); } - /** Stores the decoded argument; SKIP leaves it absent when the selected codec decodes null. */ + /** + * Stores the decoded argument. SKIP leaves it absent when the selected codec decodes null; + * unboxed carriers are stored as decoded, like generated readers and property paths. + */ public void readUtf16(Utf16JsonReader reader, Object[] arguments) { - Object value = readUtf16Value(reader); + if (readOccurrenceNull(reader)) { + arguments[argumentIndex] = null; + return; + } + if (unboxedValueCodec != null) { + arguments[argumentIndex] = + requirePrimitive(unboxedValueCodec.readUtf16Carrier(reader), rawType); + return; + } + Object value = typeInfo.utf16Reader().readUtf16(reader); if (value != null || onNullRead != NullHandling.SKIP) { - arguments[argumentIndex] = value; + arguments[argumentIndex] = requirePrimitive(value, rawType); } } /** - * Decodes one argument value. Under SKIP, callers have already consumed an explicit JSON null, so - * a null result means the selected codec decoded null and the argument stays absent. + * Decodes a SKIP argument through its codec before an unwrapped group exists. The caller has + * already consumed an explicit JSON null, so null means the argument stays absent. */ public Object readUtf16Value(Utf16JsonReader reader) { - if (readOccurrenceNull(reader)) { - return null; - } - Object value = - unboxedValueCodec == null - ? typeInfo.utf16Reader().readUtf16(reader) - : unboxedValueCodec.readUtf16Carrier(reader); - return value == null && onNullRead == NullHandling.SKIP - ? null - : requirePrimitive(value, rawType); + Object value = typeInfo.utf16Reader().readUtf16(reader); + return value == null ? null : requirePrimitive(value, rawType); } - /** Stores the decoded argument; SKIP leaves it absent when the selected codec decodes null. */ + /** + * Stores the decoded argument. SKIP leaves it absent when the selected codec decodes null; + * unboxed carriers are stored as decoded, like generated readers and property paths. + */ public void readUtf8(Utf8JsonReader reader, Object[] arguments) { - Object value = readUtf8Value(reader); + if (readOccurrenceNull(reader)) { + arguments[argumentIndex] = null; + return; + } + if (unboxedValueCodec != null) { + arguments[argumentIndex] = + requirePrimitive(unboxedValueCodec.readUtf8Carrier(reader), rawType); + return; + } + Object value = typeInfo.utf8Reader().readUtf8(reader); if (value != null || onNullRead != NullHandling.SKIP) { - arguments[argumentIndex] = value; + arguments[argumentIndex] = requirePrimitive(value, rawType); } } /** - * Decodes one argument value. Under SKIP, callers have already consumed an explicit JSON null, so - * a null result means the selected codec decoded null and the argument stays absent. + * Decodes a SKIP argument through its codec before an unwrapped group exists. The caller has + * already consumed an explicit JSON null, so null means the argument stays absent. */ public Object readUtf8Value(Utf8JsonReader reader) { - if (readOccurrenceNull(reader)) { - return null; - } - Object value = - unboxedValueCodec == null - ? typeInfo.utf8Reader().readUtf8(reader) - : unboxedValueCodec.readUtf8Carrier(reader); - return value == null && onNullRead == NullHandling.SKIP - ? null - : requirePrimitive(value, rawType); + Object value = typeInfo.utf8Reader().readUtf8(reader); + return value == null ? null : requirePrimitive(value, rawType); } private boolean readOccurrenceNull(org.apache.fory.json.reader.JsonReader reader) {