diff --git a/docs/json/annotations.md b/docs/json/annotations.md index 69deba4065..27d4cf802b 100644 --- a/docs/json/annotations.md +++ b/docs/json/annotations.md @@ -235,9 +235,15 @@ checks. A skipped duplicate does not erase an earlier value: `{"seats":["a"],"se 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` 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. +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 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 efa517df0f..f4b31439aa 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -130,8 +130,11 @@ 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 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. 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..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 @@ -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, 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 0661492486..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 @@ -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, AtomicReferenceArray, + * 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..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 @@ -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; @@ -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); @@ -986,7 +993,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; @@ -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); @@ -1066,7 +1080,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; @@ -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(); - ((Object[]) workspace)[field.argumentIndex()] = field.readLatin1(reader); + 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.decodesBeforeGroup()) { + // 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(); - ((Object[]) workspace)[field.argumentIndex()] = field.readUtf16(reader); + 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.decodesBeforeGroup()) { + // 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(); - ((Object[]) workspace)[field.argumentIndex()] = field.readUtf8(reader); + 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.decodesBeforeGroup()) { + // 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(',')); @@ -1449,7 +1547,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); @@ -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); } @@ -1506,7 +1607,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); @@ -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); } @@ -1563,7 +1667,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); @@ -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); } @@ -1617,7 +1724,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 +1759,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 +1794,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(',')); @@ -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/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..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 @@ -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( @@ -801,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, @@ -817,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( @@ -1047,6 +1050,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 +1059,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 +1106,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 +1694,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 +1725,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 +2614,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")); @@ -2635,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 = @@ -2646,14 +2693,31 @@ 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( - 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.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(); @@ -4062,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 = @@ -4080,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 = @@ -4122,7 +4182,7 @@ private Expression readUnknown( name, new Expression.Invoke(ownerRef(), "reserveAnyEntry", readerRef()), value, - write); + skipDecodedAnyNull(value, write)); } return new Expression.If( reserved, @@ -4133,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)), @@ -5159,7 +5235,14 @@ 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 = readDecodedValue(property, id); + return new Expression.If( + notNull(decoded), builder.setField(property, object, resolvedValue(property, id, decoded))); } final Expression readCollection( @@ -5173,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); @@ -5208,14 +5318,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..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,37 +200,91 @@ 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; + * unboxed carriers are stored as decoded, like generated readers and property paths. + */ + public void readLatin1(Latin1JsonReader reader, Object[] arguments) { if (readOccurrenceNull(reader)) { - return null; + arguments[argumentIndex] = null; + return; + } + if (unboxedValueCodec != null) { + arguments[argumentIndex] = + requirePrimitive(unboxedValueCodec.readLatin1Carrier(reader), rawType); + return; } - Object value = - unboxedValueCodec == null - ? typeInfo.latin1Reader().readLatin1(reader) - : unboxedValueCodec.readLatin1Carrier(reader); - return requirePrimitive(value, rawType); + Object value = typeInfo.latin1Reader().readLatin1(reader); + if (value != null || onNullRead != NullHandling.SKIP) { + arguments[argumentIndex] = requirePrimitive(value, rawType); + } + } + + /** + * 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) { + Object value = typeInfo.latin1Reader().readLatin1(reader); + return value == null ? null : requirePrimitive(value, rawType); } - public Object readUtf16(Utf16JsonReader reader) { + /** + * 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) { if (readOccurrenceNull(reader)) { - return null; + 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] = requirePrimitive(value, rawType); } - Object value = - unboxedValueCodec == null - ? typeInfo.utf16Reader().readUtf16(reader) - : unboxedValueCodec.readUtf16Carrier(reader); - return requirePrimitive(value, rawType); } - public Object readUtf8(Utf8JsonReader reader) { + /** + * 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) { + 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; + * unboxed carriers are stored as decoded, like generated readers and property paths. + */ + 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 (unboxedValueCodec != null) { + arguments[argumentIndex] = + requirePrimitive(unboxedValueCodec.readUtf8Carrier(reader), rawType); + return; + } + Object value = typeInfo.utf8Reader().readUtf8(reader); + if (value != null || onNullRead != NullHandling.SKIP) { + arguments[argumentIndex] = requirePrimitive(value, rawType); + } + } + + /** + * 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) { + Object value = typeInfo.utf8Reader().readUtf8(reader); + return value == null ? 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 7b756e80bb..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,40 @@ 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) { + return; + } + 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 = @@ -1073,14 +1107,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 +1170,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 +1233,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..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; @@ -94,7 +97,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 +107,112 @@ 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 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 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(); @@ -299,9 +410,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 +442,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 +637,86 @@ 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 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; + + @JsonCreator + public DecodedCreated(@JsonProperty("value") @JsonCodec(NullStringCodec.class) String value) { + this.value = value; + } } public static class ScalarContent { @@ -538,6 +763,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) {