From a121aac29908b3de45b7a53f7d0e9bbecea7972c Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 15:55:11 +0100 Subject: [PATCH 01/15] feat(java): opt-in lenient reading of off-spec JSON value shapes Add @JsonLenient (class, field, setter, creator parameter) and ForyJsonBuilder.lenientRead(...) to accept common off-spec input shapes per property: a single value as a one-element array or collection, numbers and booleans as String text, truncated floats for integral targets, whitespace-padded quoted scalars, and empty strings as null. Lenient properties get a read-only coercion codec in front of their Fory-owned codec when metadata is built; strict properties and their generated readers are unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/json/annotations.md | 60 ++- docs/json/object-mapping.md | 19 + .../processing/JsonMixinAnnotations.java | 2 + .../org/apache/fory/json/ForyJsonBuilder.java | 26 ++ .../java/org/apache/fory/json/JsonConfig.java | 13 + .../fory/json/annotation/JsonLenient.java | 94 ++++ .../apache/fory/json/codec/ArrayCodec.java | 26 ++ .../fory/json/codec/CollectionCodec.java | 11 + .../fory/json/codec/LenientReadCodec.java | 424 ++++++++++++++++++ .../fory/json/codec/ObjectCodecBuilder.java | 72 ++- .../fory/json/meta/JsonCreatorFieldInfo.java | 15 +- .../apache/fory/json/meta/JsonFieldInfo.java | 29 +- .../apache/fory/json/reader/JsonReader.java | 159 +++++++ .../resolver/GeneratedCodecKeyBuilder.java | 7 + .../json/resolver/JsonMixinAnnotations.java | 2 + .../json/resolver/JsonSharedRegistry.java | 8 + .../fory/json/resolver/JsonTypeResolver.java | 72 +++ .../fory/json/JsonAsyncCompilationTest.java | 2 + .../org/apache/fory/json/JsonCreatorTest.java | 3 +- .../org/apache/fory/json/JsonLenientTest.java | 377 ++++++++++++++++ .../org/apache/fory/json/JsonTestSupport.java | 2 + 21 files changed, 1407 insertions(+), 16 deletions(-) create mode 100644 java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java create mode 100644 java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java create mode 100644 java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java diff --git a/docs/json/annotations.md b/docs/json/annotations.md index 69deba4065..7405d8bae8 100644 --- a/docs/json/annotations.md +++ b/docs/json/annotations.md @@ -22,7 +22,7 @@ license: | Fory JSON provides these mapping and validation annotations in `org.apache.fory.json.annotation`: `JsonAnyGetter`, `JsonAnyProperty`, `JsonAnySetter`, `JsonByteArray`, `JsonCodec`, `JsonCreator`, -`JsonDuplicateProperties`, `JsonFormat`, `JsonIgnore`, `JsonInclude`, `JsonProperty`, `JsonPropertyOrder`, `JsonRawValue`, `JsonSubTypes`, `JsonUnwrapped`, +`JsonDuplicateProperties`, `JsonFormat`, `JsonIgnore`, `JsonInclude`, `JsonLenient`, `JsonProperty`, `JsonPropertyOrder`, `JsonRawValue`, `JsonSubTypes`, `JsonUnwrapped`, `JsonValidator`, and `JsonValue`. `JsonType` is a separate build-time model marker. They are Fory JSON APIs, not Jackson, Gson, or Fory binary-protocol compatibility annotations. @@ -374,6 +374,64 @@ inherited by subclasses, and an exact-target Mixin can supply or replace it. It class is read as a JSON object: a class read through `JsonValue`, `JsonCodec`, a registered codec, or as an enum is unaffected. Writing is unaffected. +## `JsonLenient` + +`JsonLenient` accepts common off-spec value shapes when reading a property. Each feature is +independent; the annotation without arguments enables all of them: + +| Feature | Accepts | Target | +| ----------------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------- | +| `SINGLE_VALUE_AS_ARRAY` | a value other than an array or `null` as a one-element array, for example `"IAB1"` | arrays (except binary-encoded `byte[]`) and collections | +| `SCALAR_AS_STRING` | a number or boolean as its exact token text, for example `1.50` as `"1.50"` | `String` | +| `FLOAT_AS_INT` | a number with a fraction or exponent, truncated toward zero: `300.7` as `300`, `1e3` | `byte`, `short`, `int`, `long`, their boxed types, and `BigInteger` | +| `TRIM_QUOTED_SCALAR` | a quoted boolean or number with surrounding whitespace, for example `" 300 "` | boolean and numeric types | +| `EMPTY_STRING_AS_NULL` | `""` as `null`; primitives receive `false` or zero | boolean, numeric, object, map, array, and collection types | + +```java +import org.apache.fory.json.annotation.JsonLenient; +import org.apache.fory.json.annotation.JsonLenient.Feature; + +@JsonLenient +public final class Imp { + public String id; + public List cat; + public int w; + + @JsonLenient({}) + public List strictCat; + + @JsonLenient(Feature.SINGLE_VALUE_AS_ARRAY) + public List banners; +} +``` + +With this model, `{"id":123,"cat":"IAB1","w":"300.0"}` reads `id` as `"123"`, `cat` as `[IAB1]`, and +`w` as `300`, while `strictCat` still requires a JSON array. + +A declaration on a field, setter, or `JsonCreator` parameter replaces the class and builder settings +for that logical property, and `@JsonLenient({})` makes one property strict. A class declaration is +the default for every property of that class and replaces the builder's `lenientRead` setting. It is +not inherited by subclasses and does not apply to nested objects, which follow their own class +setting. An exact-target Mixin can supply or replace either declaration. + +Features apply to the property value and to the direct boolean, numeric, and string elements of a +property-owned array or collection, so `["1", 2.9, ""]` read into `List` with all features +is `[1, 2, null]`. They apply only where Fory owns the representation: properties with `JsonCodec`, +`JsonFormat`, `JsonByteArray`, a registered codec, or a `JsonValue` type keep their representation. +A class or builder setting applies silently wherever a feature fits the property type. A property +declaration with no feature that fits the property type, or one on a property that selects its own +representation, an Any member, or an unwrapped property, is rejected when the class metadata is +built. + +Additional rules: + +- Truncation still fails for values outside the target range. `TRIM_QUOTED_SCALAR` does not accept + escape sequences or anything other than one token between the whitespace. +- An empty string read into an array or collection is `null`, not a one-element array. +- An empty string is a decoded value, not an explicit JSON null, so `JsonProperty.onNullRead` does + not apply to it. +- Root values, map values, and optional contents are not affected. Writing is unaffected. + ## `JsonPropertyOrder` `JsonPropertyOrder` combines a named serialization prefix, property indexes, and final-name diff --git a/docs/json/object-mapping.md b/docs/json/object-mapping.md index c66fe52370..cb1fa5b3fb 100644 --- a/docs/json/object-mapping.md +++ b/docs/json/object-mapping.md @@ -153,6 +153,25 @@ The read fails with a `ForyJsonException` that names the repeated property. To enable or disable the check for one class, annotate it with `JsonDuplicateProperties`; see [Annotations](annotations.md#jsonduplicateproperties). This option does not change writing. +## Lenient reading + +Reading is strict by default: apart from quoted booleans and numbers, each declared type accepts only +its own JSON shape. Input from third parties often contains off-spec shapes that other JSON libraries +accept, such as a lone string for a list, a number for a string, `300.0` or `" 300 "` for an `int`, +or `""` for an absent number. Enable the matching features for every property with `lenientRead`: + +```java +ForyJson json = ForyJson.builder() + .lenientRead(JsonLenient.Feature.SINGLE_VALUE_AS_ARRAY, JsonLenient.Feature.FLOAT_AS_INT) + .build(); +``` + +No feature is enabled by default. A feature applies only to properties whose type and Fory-owned +representation it fits; strict properties keep their normal read path and cost. To enable features +for one class or property, or to keep one property strict, use `JsonLenient`; see +[Annotations](annotations.md#jsonlenient) for the features and their exact behavior. Root values, +map values, and optional contents are not affected. This option does not change writing. + ## Kotlin object mapping Install `fory-json-kotlin` and use `ForyJsonKotlin.builder()` for Kotlin/JVM classes. Kotlin diff --git a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonMixinAnnotations.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonMixinAnnotations.java index e6c0e27951..768bac7e73 100644 --- a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonMixinAnnotations.java +++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonMixinAnnotations.java @@ -61,6 +61,7 @@ final class JsonMixinAnnotations { private static final String JSON_FORMAT = JSON_PACKAGE + ".annotation.JsonFormat"; private static final String JSON_IGNORE = JSON_PACKAGE + ".annotation.JsonIgnore"; private static final String JSON_INCLUDE = JSON_PACKAGE + ".annotation.JsonInclude"; + private static final String JSON_LENIENT = JSON_PACKAGE + ".annotation.JsonLenient"; private static final String JSON_PROPERTY = JSON_PACKAGE + ".annotation.JsonProperty"; private static final String JSON_PROPERTY_ORDER = JSON_PACKAGE + ".annotation.JsonPropertyOrder"; private static final String JSON_RAW_VALUE = JSON_PACKAGE + ".annotation.JsonRawValue"; @@ -83,6 +84,7 @@ final class JsonMixinAnnotations { JSON_FORMAT, JSON_IGNORE, JSON_INCLUDE, + JSON_LENIENT, JSON_PROPERTY, JSON_PROPERTY_ORDER, JSON_RAW_VALUE, 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..bf3359f0fd 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 @@ -20,11 +20,13 @@ package org.apache.fory.json; import java.util.ArrayList; +import java.util.EnumSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.apache.fory.json.annotation.JsonByteArray; +import org.apache.fory.json.annotation.JsonLenient; import org.apache.fory.json.annotation.JsonMixin; import org.apache.fory.json.annotation.JsonProperty.Include; import org.apache.fory.json.annotation.JsonProperty.NullHandling; @@ -59,6 +61,8 @@ public final class ForyJsonBuilder { private boolean escapeNonAscii; private boolean failOnMissingRequiredProperties; private boolean failOnDuplicateProperties; + private final EnumSet lenientRead = + EnumSet.noneOf(JsonLenient.Feature.class); private JsonByteArray.Format byteArrayFormat = JsonByteArray.Format.BASE64; private boolean codegenEnabled = true; private boolean asyncCompilationEnabled = true; @@ -221,6 +225,27 @@ public ForyJsonBuilder failOnDuplicateProperties(boolean enabled) { return this; } + /** + * Sets the lenient read features applied to every object property without its own or its class's + * {@link JsonLenient} declaration. No feature is enabled by default, so reading is strict. + * + *

Each call replaces the previous set. A feature applies only to properties whose type and + * Fory-owned representation it fits; see {@link JsonLenient} for the exact behavior. Root values, + * map values, and optional contents are not affected. Writing is unaffected. + * + * @throws NullPointerException if the array or one of its features is null + */ + public ForyJsonBuilder lenientRead(JsonLenient.Feature... features) { + Objects.requireNonNull(features, "features"); + EnumSet selected = EnumSet.noneOf(JsonLenient.Feature.class); + for (JsonLenient.Feature feature : features) { + selected.add(Objects.requireNonNull(feature, "feature")); + } + lenientRead.clear(); + lenientRead.addAll(selected); + return this; + } + /** * Sets the default representation for {@code byte[]} roots, properties, and container values in * both reading and writing. The default is {@link JsonByteArray.Format#BASE64}. @@ -460,6 +485,7 @@ JsonConfig buildConfig() { escapeNonAscii, failOnMissingRequiredProperties, failOnDuplicateProperties, + lenientRead, byteArrayFormat, effectiveCodegen, effectiveAsyncCompilation, diff --git a/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java b/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java index 3f4615baf8..252a522c76 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/JsonConfig.java @@ -20,12 +20,15 @@ package org.apache.fory.json; import java.util.Collections; +import java.util.EnumSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import org.apache.fory.annotation.Internal; import org.apache.fory.json.annotation.JsonByteArray; +import org.apache.fory.json.annotation.JsonLenient; import org.apache.fory.json.annotation.JsonProperty.Include; import org.apache.fory.json.annotation.JsonProperty.NullHandling; import org.apache.fory.json.resolver.CodecRegistry; @@ -46,6 +49,7 @@ public final class JsonConfig { private final boolean escapeNonAscii; private final boolean failOnMissingRequiredProperties; private final boolean failOnDuplicateProperties; + private final Set lenientRead; private final JsonByteArray.Format byteArrayFormat; private final boolean codegenEnabled; private final boolean asyncCompilationEnabled; @@ -72,6 +76,7 @@ public final class JsonConfig { boolean escapeNonAscii, boolean failOnMissingRequiredProperties, boolean failOnDuplicateProperties, + Set lenientRead, JsonByteArray.Format byteArrayFormat, boolean codegenEnabled, boolean asyncCompilationEnabled, @@ -95,6 +100,9 @@ public final class JsonConfig { this.escapeNonAscii = escapeNonAscii; this.failOnMissingRequiredProperties = failOnMissingRequiredProperties; this.failOnDuplicateProperties = failOnDuplicateProperties; + EnumSet features = EnumSet.noneOf(JsonLenient.Feature.class); + features.addAll(lenientRead); + this.lenientRead = Collections.unmodifiableSet(features); this.byteArrayFormat = Objects.requireNonNull(byteArrayFormat, "byteArrayFormat"); this.codegenEnabled = codegenEnabled; this.asyncCompilationEnabled = asyncCompilationEnabled; @@ -157,6 +165,11 @@ public boolean failOnDuplicateProperties() { return failOnDuplicateProperties; } + /** Returns the lenient read features applied to properties without a declared setting. */ + public Set lenientRead() { + return lenientRead; + } + /** Returns the default byte-array representation for both reading and writing. */ public JsonByteArray.Format byteArrayFormat() { return byteArrayFormat; diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java new file mode 100644 index 0000000000..69726e9122 --- /dev/null +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fory.json.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Accepts common off-spec JSON value shapes when reading a property, as Jackson does by default or + * behind its well-known coercion switches. + * + *

On a field, setter, or {@link JsonCreator} parameter, the listed features replace the class + * and builder settings for that logical property; {@code @JsonLenient({})} makes one property + * strict. On a class, they are the default for every property of that class and replace {@code + * ForyJsonBuilder.lenientRead}. A class annotation is not inherited by subclasses and does not + * apply to nested objects, which follow their own class setting. An exact-target {@link JsonMixin} + * may supply or replace either declaration. + * + *

Features apply to the property value and to the direct boolean, numeric, and string elements + * of a property-owned array or collection. They apply only where Fory owns the representation: a + * property with {@link JsonCodec}, {@link JsonFormat}, {@link JsonByteArray}, {@link JsonRawValue}, + * {@link JsonUnwrapped}, a registered codec, or a {@link JsonValue} type keeps that representation. + * A class or builder setting applies silently wherever a feature fits the property type; a property + * declaration without any feature that fits its type is rejected when metadata is built. Root + * values, map values, and optional contents are not affected. Writing is unaffected. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) +public @interface JsonLenient { + /** Returns the enabled features; the default enables all of them. */ + Feature[] value() default { + Feature.SINGLE_VALUE_AS_ARRAY, + Feature.SCALAR_AS_STRING, + Feature.FLOAT_AS_INT, + Feature.TRIM_QUOTED_SCALAR, + Feature.EMPTY_STRING_AS_NULL + }; + + /** Independently selectable read coercions. */ + enum Feature { + /** + * A JSON value other than an array or {@code null} read into an array or collection is read as + * its single element, for example {@code "IAB1"} into {@code List}. Byte arrays encoded + * as binary strings are not affected. + */ + SINGLE_VALUE_AS_ARRAY, + /** + * A JSON number or boolean read into a {@code String} is kept as its exact token text, for + * example {@code 1.50} as {@code "1.50"}. + */ + SCALAR_AS_STRING, + /** + * A JSON number with a fraction or exponent read into a {@code byte}, {@code short}, {@code + * int}, {@code long}, their boxed types, or {@code BigInteger} is truncated toward zero, for + * example {@code 300.7} as {@code 300} and {@code 1e3} as {@code 1000}. Values outside the + * target range still fail. Quoted numbers are truncated the same way. + */ + FLOAT_AS_INT, + /** + * A quoted boolean or number read into a boolean or numeric target may have leading and + * trailing JSON whitespace inside the quotes, for example {@code " 300 "}. + */ + TRIM_QUOTED_SCALAR, + /** + * An empty JSON string read into a boolean, numeric, object, map, array, or collection target + * is read as {@code null}; primitive targets receive {@code false} or zero. With {@link + * #TRIM_QUOTED_SCALAR}, a whitespace-only string read into a boolean or numeric target is also + * empty. The value is assigned like any other decoded value: explicit-null handling does not + * apply. Text targets such as strings, enums, and date/time values are not affected. + */ + EMPTY_STRING_AS_NULL + } +} 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..cc847c2d90 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 @@ -67,6 +67,12 @@ public abstract class ArrayCodec implements ContainerJsonCodec { @Internal public abstract ArrayCodec withContentNullRead(NullHandling handling); + /** Returns this array's effective immediate-element null handling. */ + @Internal + public final NullHandling onContentNullRead() { + return onContentNullRead; + } + public static JsonValueCodec create( Class arrayType, TypeRef arrayTypeRef, JsonTypeResolver resolver) { if (!arrayType.isArray()) { @@ -233,6 +239,26 @@ static void finishReferenceArray(JsonReader reader, int size) { reader.exitDepth(); } + /** + * Builds the array that a lenient single-value read produces from one decoded element. The array + * header and its single slot are reserved like any other one-element array. + */ + static Object singleElementArray(JsonReader reader, Class componentType, Object element) { + if (componentType.isPrimitive()) { + if (element == null) { + throw new ForyJsonException( + "Cannot read null into primitive array element " + componentType); + } + reader.reserveGraphMemory( + ARRAY_HEADER_BYTES + TypeUtils.getSizeOfPrimitiveType(componentType)); + } else { + reader.reserveGraphMemory(ARRAY_HEADER_BYTES + REFERENCE_BYTES); + } + Object array = Array.newInstance(componentType, 1); + Array.set(array, 0, element); + return array; + } + static void finishPrimitiveArray(JsonReader reader, int size, int elementBytes) { int tailSize = size & ARRAY_BATCH_MASK; reader.reserveGraphMemory(ARRAY_HEADER_BYTES + tailSize * elementBytes); 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..41fe0eb060 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 @@ -290,6 +290,17 @@ static Collection readUntyped(Utf8JsonReader reader) { return collection; } + /** + * Builds the collection that a lenient single-value read produces from one decoded element. The + * collection owner and its single reference slot are reserved like an array of one element. + */ + final Collection singleElementCollection(JsonReader reader, Object element) { + Collection collection = newCollection(reader); + reader.reserveGraphMemory(REFERENCE_BYTES); + collection.add(requireElement(elementTypeInfo, element)); + return finishCollection(reader, collection); + } + @Internal final Collection newCollection(JsonReader reader) { // JSON arrays do not carry a trusted size. Avoid speculative backing-array preallocation in diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java new file mode 100644 index 0000000000..d0da70a3d2 --- /dev/null +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java @@ -0,0 +1,424 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fory.json.codec; + +import org.apache.fory.annotation.Internal; +import org.apache.fory.json.ForyJsonException; +import org.apache.fory.json.annotation.JsonLenient; +import org.apache.fory.json.reader.JsonReader; +import org.apache.fory.json.reader.Latin1JsonReader; +import org.apache.fory.json.reader.Utf16JsonReader; +import org.apache.fory.json.reader.Utf8JsonReader; +import org.apache.fory.json.resolver.JsonTypeInfo; +import org.apache.fory.json.writer.JsonWriter; +import org.apache.fory.json.writer.StringJsonWriter; +import org.apache.fory.json.writer.Utf8JsonWriter; + +/** + * Read-only coercion in front of one property occurrence's Fory-owned codec, selected when the + * property's metadata is built from its effective {@link JsonLenient} features. + * + *

Strict properties never reference this codec. A lenient property dispatches its off-spec + * shapes here and delegates every native token to the wrapped occurrence's current reader slot, so + * generated object and collection capabilities installed in that slot remain in use. Writing always + * delegates unchanged. + */ +@Internal +public abstract class LenientReadCodec implements JsonValueCodec { + public static final int SINGLE_VALUE_AS_ARRAY = bit(JsonLenient.Feature.SINGLE_VALUE_AS_ARRAY); + public static final int SCALAR_AS_STRING = bit(JsonLenient.Feature.SCALAR_AS_STRING); + public static final int FLOAT_AS_INT = bit(JsonLenient.Feature.FLOAT_AS_INT); + public static final int TRIM_QUOTED_SCALAR = bit(JsonLenient.Feature.TRIM_QUOTED_SCALAR); + public static final int EMPTY_STRING_AS_NULL = bit(JsonLenient.Feature.EMPTY_STRING_AS_NULL); + + /** + * Marks a property mask that comes from the property's own declaration rather than its class or + * builder default. Such a declaration must have at least one feature that fits the property. + */ + public static final int DECLARED = 1 << 31; + + /** Selects the feature bits of a property mask. */ + public static final int FEATURES = ~DECLARED; + + private static final int INT_TARGET = 1; + private static final int LONG_TARGET = 2; + private static final int SHORT_TARGET = 3; + private static final int BYTE_TARGET = 4; + private static final int BIG_INTEGER_TARGET = 5; + + final JsonTypeInfo base; + + LenientReadCodec(JsonTypeInfo base) { + this.base = base; + } + + private static int bit(JsonLenient.Feature feature) { + return 1 << feature.ordinal(); + } + + /** Returns the feature mask of the given features. */ + public static int mask(Iterable features) { + int mask = 0; + for (JsonLenient.Feature feature : features) { + mask |= bit(feature); + } + return mask; + } + + /** Returns the feature mask of one declaration. */ + public static int mask(JsonLenient declaration) { + int mask = 0; + for (JsonLenient.Feature feature : declaration.value()) { + mask |= bit(feature); + } + return mask; + } + + /** + * Returns the lenient codec for a scalar occurrence, or {@code null} when none of the features + * applies to its exact Fory-owned codec. + */ + public static LenientReadCodec scalar(JsonTypeInfo base, int features) { + Object codec = base.valueCodec(); + if (codec == ScalarCodecs.StringCodec.INSTANCE) { + return (features & SCALAR_AS_STRING) == 0 ? null : new TextCodec(base); + } + int scalarFeatures = features & (TRIM_QUOTED_SCALAR | EMPTY_STRING_AS_NULL); + Object empty = null; + int integral = 0; + if (codec == ScalarCodecs.BooleanCodec.PRIMITIVE) { + empty = Boolean.FALSE; + } else if (codec == ScalarCodecs.IntCodec.PRIMITIVE) { + empty = 0; + integral = INT_TARGET; + } else if (codec == ScalarCodecs.LongCodec.PRIMITIVE + || codec == ScalarCodecs.LongAsStringCodec.PRIMITIVE) { + empty = 0L; + integral = LONG_TARGET; + } else if (codec == ScalarCodecs.ShortCodec.PRIMITIVE) { + empty = (short) 0; + integral = SHORT_TARGET; + } else if (codec == ScalarCodecs.ByteCodec.PRIMITIVE) { + empty = (byte) 0; + integral = BYTE_TARGET; + } else if (codec == ScalarCodecs.FloatCodec.PRIMITIVE) { + empty = 0f; + } else if (codec == ScalarCodecs.DoubleCodec.PRIMITIVE) { + empty = 0d; + } else if (codec == ScalarCodecs.IntCodec.BOXED) { + integral = INT_TARGET; + } else if (codec == ScalarCodecs.LongCodec.BOXED + || codec == ScalarCodecs.LongAsStringCodec.BOXED) { + integral = LONG_TARGET; + } else if (codec == ScalarCodecs.ShortCodec.BOXED) { + integral = SHORT_TARGET; + } else if (codec == ScalarCodecs.ByteCodec.BOXED) { + integral = BYTE_TARGET; + } else if (codec == ScalarCodecs.BigIntegerCodec.INSTANCE) { + integral = BIG_INTEGER_TARGET; + } else if (codec != ScalarCodecs.BooleanCodec.BOXED + && codec != ScalarCodecs.FloatCodec.BOXED + && codec != ScalarCodecs.DoubleCodec.BOXED + && codec != ScalarCodecs.BigDecimalCodec.INSTANCE) { + return null; + } + if (integral != 0) { + scalarFeatures |= features & FLOAT_AS_INT; + } + return scalarFeatures == 0 ? null : new ScalarCodec(base, scalarFeatures, integral, empty); + } + + /** + * Returns the lenient codec for an array, collection, map, or object occurrence, or {@code null} + * when none of the features applies to its exact Fory-owned codec. {@code element} is the + * occurrence's element type information used for single-value reads. + */ + public static LenientReadCodec container(JsonTypeInfo base, JsonTypeInfo element, int features) { + Object codec = base.valueCodec(); + boolean array = codec instanceof ArrayCodec; + boolean collection = codec instanceof CollectionCodec; + int containerFeatures = features & EMPTY_STRING_AS_NULL; + if (array || collection) { + containerFeatures |= features & SINGLE_VALUE_AS_ARRAY; + } else if (!(codec instanceof MapCodec) && !(codec instanceof ObjectCodec)) { + return null; + } + if (containerFeatures == 0) { + return null; + } + if ((containerFeatures & SINGLE_VALUE_AS_ARRAY) == 0) { + element = null; + } + return array + ? new ArrayElementCodec(base, element, containerFeatures, base.rawType().getComponentType()) + : new ContainerCodec(base, element, containerFeatures); + } + + @Override + public final void writeString(StringJsonWriter writer, Object value) { + base.stringWriter().writeString(writer, value); + } + + @Override + public final void writeUtf8(Utf8JsonWriter writer, Object value) { + base.utf8Writer().writeUtf8(writer, value); + } + + @Override + public final boolean isEmpty(JsonWriter writer, Object value) { + return base.valueCodec().isEmpty(writer, value); + } + + /** Keeps a JSON number or boolean read into a String as its token text. */ + private static final class TextCodec extends LenientReadCodec { + private TextCodec(JsonTypeInfo base) { + super(base); + } + + // Returns null when the next token is not a native number or boolean. + private static String readScalarText(JsonReader reader) { + char token = reader.peekToken(); + if (token == '-' || token >= '0' && token <= '9') { + return reader.readNumberAsString(); + } + if (token == 't' || token == 'f') { + return reader.readBoolean() ? "true" : "false"; + } + return null; + } + + @Override + public Object readLatin1(Latin1JsonReader reader) { + String text = readScalarText(reader); + return text != null ? text : base.latin1Reader().readLatin1(reader); + } + + @Override + public Object readUtf16(Utf16JsonReader reader) { + String text = readScalarText(reader); + return text != null ? text : base.utf16Reader().readUtf16(reader); + } + + @Override + public Object readUtf8(Utf8JsonReader reader) { + String text = readScalarText(reader); + return text != null ? text : base.utf8Reader().readUtf8(reader); + } + } + + /** Coerces padded, empty, and fractional input for boolean and numeric targets. */ + private static final class ScalarCodec extends LenientReadCodec { + // Distinguishes "decoded a null" from "the native reader owns this token". + private static final Object NATIVE = new Object(); + private static final Object EMPTY_REFERENCE = new Object(); + private static final Object PADDED = new Object(); + + private final boolean emptyAsNull; + private final boolean trim; + private final boolean truncate; + private final int integral; + private final Object empty; + + private ScalarCodec(JsonTypeInfo base, int features, int integral, Object empty) { + super(base); + emptyAsNull = (features & EMPTY_STRING_AS_NULL) != 0; + trim = (features & TRIM_QUOTED_SCALAR) != 0; + truncate = (features & FLOAT_AS_INT) != 0; + this.integral = integral; + this.empty = empty == null ? EMPTY_REFERENCE : empty; + } + + // Consumes an empty string or the opening of a padded string. Returns EMPTY_REFERENCE or a + // primitive zero for an empty string, PADDED after a padded opening, and NATIVE otherwise. + private Object begin(JsonReader reader) { + if (reader.peekToken() != '"') { + return NATIVE; + } + if (emptyAsNull && reader.tryReadEmptyString(trim)) { + return empty; + } + if (trim && reader.beginPaddedQuotedScalar()) { + if (reader.peekToken() == 'n') { + throw new ForyJsonException("Expected a quoted boolean or number"); + } + return PADDED; + } + return NATIVE; + } + + private Object readTruncated(JsonReader reader) { + if (reader.peekToken() == 'n') { + return NATIVE; + } + if (integral == BIG_INTEGER_TARGET) { + return reader.readTruncatedBigInteger(); + } + long value = reader.readTruncatedLong(); + switch (integral) { + case INT_TARGET: + if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { + throw new ForyJsonException("Integer overflow"); + } + return (int) value; + case SHORT_TARGET: + if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) { + throw new ForyJsonException("Short overflow"); + } + return (short) value; + case BYTE_TARGET: + if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) { + throw new ForyJsonException("Byte overflow"); + } + return (byte) value; + default: + return value; + } + } + + private Object finish(JsonReader reader, Object opening, Object value) { + if (opening == PADDED) { + reader.finishPaddedQuotedScalar(); + } + return value; + } + + @Override + public Object readLatin1(Latin1JsonReader reader) { + Object opening = begin(reader); + if (opening != NATIVE && opening != PADDED) { + return opening == EMPTY_REFERENCE ? null : opening; + } + Object value = truncate ? readTruncated(reader) : NATIVE; + if (value == NATIVE) { + value = base.latin1Reader().readLatin1(reader); + } + return finish(reader, opening, value); + } + + @Override + public Object readUtf16(Utf16JsonReader reader) { + Object opening = begin(reader); + if (opening != NATIVE && opening != PADDED) { + return opening == EMPTY_REFERENCE ? null : opening; + } + Object value = truncate ? readTruncated(reader) : NATIVE; + if (value == NATIVE) { + value = base.utf16Reader().readUtf16(reader); + } + return finish(reader, opening, value); + } + + @Override + public Object readUtf8(Utf8JsonReader reader) { + Object opening = begin(reader); + if (opening != NATIVE && opening != PADDED) { + return opening == EMPTY_REFERENCE ? null : opening; + } + Object value = truncate ? readTruncated(reader) : NATIVE; + if (value == NATIVE) { + value = base.utf8Reader().readUtf8(reader); + } + return finish(reader, opening, value); + } + } + + /** Reads an empty string as null and, for collections, a single value as one element. */ + private static class ContainerCodec extends LenientReadCodec { + private static final int NATIVE = 0; + private static final int EMPTY = 1; + private static final int SINGLE = 2; + + final JsonTypeInfo element; + private final boolean emptyAsNull; + + private ContainerCodec(JsonTypeInfo base, JsonTypeInfo element, int features) { + super(base); + this.element = element; + emptyAsNull = (features & EMPTY_STRING_AS_NULL) != 0; + } + + final int shape(JsonReader reader) { + char token = reader.peekToken(); + if (token == '[' || token == 'n') { + return NATIVE; + } + if (emptyAsNull && token == '"' && reader.tryReadEmptyString(false)) { + return EMPTY; + } + return element == null ? NATIVE : SINGLE; + } + + Object single(JsonReader reader, Object value) { + return ((CollectionCodec) base.valueCodec()).singleElementCollection(reader, value); + } + + @Override + public final Object readLatin1(Latin1JsonReader reader) { + switch (shape(reader)) { + case EMPTY: + return null; + case SINGLE: + return single(reader, element.latin1Reader().readLatin1(reader)); + default: + return base.latin1Reader().readLatin1(reader); + } + } + + @Override + public final Object readUtf16(Utf16JsonReader reader) { + switch (shape(reader)) { + case EMPTY: + return null; + case SINGLE: + return single(reader, element.utf16Reader().readUtf16(reader)); + default: + return base.utf16Reader().readUtf16(reader); + } + } + + @Override + public final Object readUtf8(Utf8JsonReader reader) { + switch (shape(reader)) { + case EMPTY: + return null; + case SINGLE: + return single(reader, element.utf8Reader().readUtf8(reader)); + default: + return base.utf8Reader().readUtf8(reader); + } + } + } + + /** Builds a one-element array for a single value. */ + private static final class ArrayElementCodec extends ContainerCodec { + private final Class componentType; + + private ArrayElementCodec( + JsonTypeInfo base, JsonTypeInfo element, int features, Class componentType) { + super(base, element, features); + this.componentType = componentType; + } + + @Override + Object single(JsonReader reader, Object value) { + return ArrayCodec.singleElementArray(reader, componentType, value); + } + } +} diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java index baebb5cdc1..02dde2b928 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java @@ -55,6 +55,7 @@ import org.apache.fory.json.annotation.JsonFormat; import org.apache.fory.json.annotation.JsonIgnore; import org.apache.fory.json.annotation.JsonInclude; +import org.apache.fory.json.annotation.JsonLenient; import org.apache.fory.json.annotation.JsonProperty; import org.apache.fory.json.annotation.JsonProperty.Include; import org.apache.fory.json.annotation.JsonProperty.NullHandling; @@ -177,6 +178,13 @@ boolean record = + " on " + type.getName()); } + if (anyBuilder != null && anyBuilder.lenientAnnotation != null) { + throw new ForyJsonException( + "@JsonLenient is not supported on JSON Any logical property " + + anyBuilder.name + + " on " + + type.getName()); + } if (anyBuilder != null && anyBuilder.formatAnnotation != null) { throw new ForyJsonException( "@JsonFormat is not supported on JSON Any logical property " @@ -1565,7 +1573,8 @@ private static JsonCreatorInfo buildRecordCreatorInfo( builder.formatAnnotation(), builder.creatorUnboxedRequired, builder.onNullRead(), - builder.explicitContentNullRead)); + builder.explicitContentNullRead, + builder.lenientRead())); } JsonCreatorFieldInfo[] fieldArray = fields.toArray(new JsonCreatorFieldInfo[0]); rejectCreatorHashCollisions(fieldArray); @@ -1706,7 +1715,8 @@ private static JsonCreatorInfo buildCreatorInfo( builder.formatAnnotation(), builder.creatorUnboxedRequired, builder.onNullRead(), - builder.explicitContentNullRead)); + builder.explicitContentNullRead, + builder.lenientRead())); } } } else { @@ -1783,6 +1793,10 @@ private static JsonCreatorInfo buildCreatorInfo( "@JsonUnwrapped creator property has no null value or content position: " + jsonName); } + if (builder == null && annotations.has(parameters[i], JsonLenient.class)) { + throw new ForyJsonException( + "@JsonLenient is not supported on @JsonUnwrapped creator property " + jsonName); + } if (codecAnnotation != null || valueCodecClass != null || formatAnnotation != null) { throw new ForyJsonException( "Value codecs are not supported on @JsonUnwrapped creator property " + jsonName); @@ -1817,9 +1831,10 @@ private static JsonCreatorInfo buildCreatorInfo( ? effectiveNullHandling( property.onNullRead(), annotations.registry.onNullRead()) : builder.onNullRead(), + builder == null ? property.onContentNullRead() : builder.explicitContentNullRead, builder == null - ? property.onContentNullRead() - : builder.explicitContentNullRead)); + ? lenientRead(annotations.get(parameters[i], JsonLenient.class), annotations) + : builder.lenientRead())); } } } @@ -1960,7 +1975,8 @@ private static JsonCreatorInfo buildObjectModelCreatorInfo( builder.formatAnnotation(), builder.creatorUnboxedRequired, builder.onNullRead(), - builder.explicitContentNullRead)); + builder.explicitContentNullRead, + builder.lenientRead())); } } JsonCreatorFieldInfo[] fieldArray = fields.toArray(new JsonCreatorFieldInfo[0]); @@ -3109,10 +3125,14 @@ private static Type boxedType(Type type) { private static final class Annotations { private final Class targetType; private final JsonSharedRegistry registry; + // The class declaration replaces the builder default for every property of this class. + private final int lenientRead; private Annotations(Class targetType, JsonSharedRegistry registry) { this.targetType = targetType; this.registry = registry; + JsonLenient lenient = registry.annotation(targetType, targetType, JsonLenient.class); + lenientRead = lenient == null ? registry.lenientRead() : LenientReadCodec.mask(lenient); } private A get(AnnotatedElement element, Class annotationType) { @@ -3124,6 +3144,12 @@ private boolean has(AnnotatedElement element, Class annota } } + private static int lenientRead(JsonLenient declared, Annotations annotations) { + return declared == null + ? annotations.lenientRead + : LenientReadCodec.mask(declared) | LenientReadCodec.DECLARED; + } + private static NullHandling effectiveNullHandling(NullHandling declared, NullHandling fallback) { return declared == NullHandling.DEFAULT ? fallback : declared; } @@ -3159,6 +3185,8 @@ private static final class FieldBuilder { private Class> valueCodecClass; private JsonFormat formatAnnotation; private AnnotatedElement formatSource; + private JsonLenient lenientAnnotation; + private AnnotatedElement lenientSource; private AnnotatedElement codecSource; private JsonUnwrapped unwrappedAnnotation; private AnnotatedElement unwrappedSource; @@ -3312,6 +3340,7 @@ private boolean hasConfiguration() { || rawValueSource != null || valueCodecClass != null || formatAnnotation != null + || lenientAnnotation != null || unwrappedAnnotation != null; } @@ -3328,6 +3357,10 @@ private NullHandling onNullRead() { return effectiveNullHandling(explicitNullRead, annotations.registry.onNullRead()); } + private int lenientRead() { + return ObjectCodecBuilder.lenientRead(lenientAnnotation, annotations); + } + private boolean hasLogicalMember() { return field != null || writeGetter != null || readSetter != null; } @@ -3429,7 +3462,8 @@ private JsonFieldInfo build( rawValue, escapeNonAscii, onNullRead(), - explicitContentNullRead); + explicitContentNullRead, + lenientRead()); } private void validateUnwrapped(Class type, JsonCreatorInfo creatorInfo) { @@ -3437,6 +3471,10 @@ private void validateUnwrapped(Class type, JsonCreatorInfo creatorInfo) { throw new ForyJsonException( "@JsonUnwrapped property has no null value or content position: " + name); } + if (lenientAnnotation != null) { + throw new ForyJsonException( + "@JsonLenient is not supported on @JsonUnwrapped property " + name); + } if (isAny()) { throw new ForyJsonException( "@JsonUnwrapped cannot share a JSON Any logical property " + name); @@ -3523,6 +3561,7 @@ private void mergeAnnotation(Class type, AnnotatedElement source) { // the backing field. Merge every declaration into the same logical property. mergeFormat(source); mergeCodec(source); + mergeLenient(source); if (annotations.has(source, JsonRawValue.class)) { if (formatAnnotation != null) { throw formatConflict(source, "@JsonRawValue"); @@ -3682,6 +3721,27 @@ private void mergeIgnore(AnnotatedElement source) { } } + private void mergeLenient(AnnotatedElement source) { + JsonLenient declared = annotations.get(source, JsonLenient.class); + if (declared == null) { + return; + } + if (lenientAnnotation != null + && LenientReadCodec.mask(lenientAnnotation) != LenientReadCodec.mask(declared)) { + throw new ForyJsonException( + "Conflicting @JsonLenient declarations for property " + + name + + " from " + + lenientSource + + " and " + + source); + } + if (lenientAnnotation == null) { + lenientAnnotation = declared; + lenientSource = source; + } + } + private void mergeUnwrapped(AnnotatedElement source) { JsonUnwrapped declared = annotations.get(source, JsonUnwrapped.class); if (declared == 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 5dd14ef03e..6cf648c243 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 @@ -52,6 +52,7 @@ public final class JsonCreatorFieldInfo { private final boolean selectedCodec; private final NullHandling onNullRead; private final NullHandling onContentNullRead; + private final int lenientRead; private JsonTypeInfo typeInfo; private JsonTypeInfo occurrenceTypeInfo; private UnboxedValueCodec unboxedValueCodec; @@ -66,9 +67,11 @@ public JsonCreatorFieldInfo( JsonFormat formatAnnotation, boolean unboxedRequired, NullHandling onNullRead, - NullHandling onContentNullRead) { + NullHandling onContentNullRead, + int lenientRead) { this.onNullRead = onNullRead; this.onContentNullRead = onContentNullRead; + this.lenientRead = lenientRead; this.name = name; nameHash = JsonFieldNameHash.hash(name); this.argumentIndex = argumentIndex; @@ -93,6 +96,11 @@ public NullHandling onContentNullRead() { return onContentNullRead; } + /** Returns the effective lenient read mask, including the declaration flag. */ + public int lenientRead() { + return lenientRead; + } + /** Leaves argument and presence state untouched for a skipped input occurrence. */ public boolean skipNullRead(JsonReader reader) { if (onNullRead == NullHandling.SET || !reader.tryReadNull()) { @@ -116,7 +124,8 @@ public JsonCreatorFieldInfo withName(String transformedName) { formatAnnotation, unboxedRequired, onNullRead, - onContentNullRead); + onContentNullRead, + lenientRead); } public long nameHash() { @@ -149,9 +158,11 @@ public void resolveType(JsonTypeResolver resolver) { resolver.withContentNullRead( selectedCodec ? selectedTypeInfo(resolver) : resolver.getTypeInfo(typeRef), onContentNullRead); + typeInfo = resolver.withLenientRead(typeInfo, lenientRead, selectedCodec, name); occurrenceTypeInfo = typeInfo; return; } + resolver.withLenientRead(null, lenientRead, true, name); if (selectedCodec) { throw new ForyJsonException( "JSON creator property " 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..c9a8633dae 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 @@ -122,6 +122,7 @@ public final class JsonFieldInfo { private final boolean readUnboxedRequired; private final NullHandling onNullRead; private final NullHandling onContentNullRead; + private final int lenientRead; private JsonFieldKind writeKind; private JsonFieldKind readKind; private int writeKindId; @@ -414,9 +415,11 @@ public JsonFieldInfo( boolean rawValue, boolean escapeNonAscii, NullHandling onNullRead, - NullHandling onContentNullRead) { + NullHandling onContentNullRead, + int lenientRead) { this.onNullRead = onNullRead; this.onContentNullRead = onContentNullRead; + this.lenientRead = lenientRead; this.name = name; this.escapeNonAscii = escapeNonAscii; // Inclusion, required-value, and read-index metadata become immutable with ObjectCodec. @@ -566,6 +569,11 @@ public NullHandling onContentNullRead() { return onContentNullRead; } + /** Returns the effective lenient read mask, including the declaration flag. */ + public int lenientRead() { + return lenientRead; + } + /** Tests the input token before decoding so transparent codecs cannot erase null presence. */ public boolean skipNullRead(JsonReader reader) { if (onNullRead == NullHandling.SET || !reader.tryReadNull()) { @@ -597,7 +605,8 @@ public JsonFieldInfo withName(String transformedName, TypeRef ownerType) { writesRawString(), escapeNonAscii, onNullRead, - onContentNullRead); + onContentNullRead, + lenientRead); copy.setReadIndex(readIndex()); copy.defaultMethod = defaultMethod; copy.defaultDependencies = defaultDependencies; @@ -980,6 +989,7 @@ public void resolveTypes(JsonTypeResolver typeResolver) { typeResolver.getTypeInfo(readTypeRef), onContentNullRead); readUnboxedValueCodec = requireUnboxed(canonical, readRawType, "read"); readOccurrenceTypeInfo = canonical; + typeResolver.withLenientRead(null, lenientRead, true, name); if (readUnboxedValueCodec instanceof DirectUnboxedValueCodec) { readTypeInfo = canonical; } else if (readUnboxedValueCodec instanceof TransparentUnboxedValueCodec) { @@ -989,9 +999,15 @@ public void resolveTypes(JsonTypeResolver typeResolver) { } } else { readTypeInfo = - typeResolver.withContentNullRead( - selectedTypeInfo == null ? typeResolver.getTypeInfo(readTypeRef) : selectedTypeInfo, - onContentNullRead); + typeResolver.withLenientRead( + typeResolver.withContentNullRead( + selectedTypeInfo == null + ? typeResolver.getTypeInfo(readTypeRef) + : selectedTypeInfo, + onContentNullRead), + lenientRead, + selectedTypeInfo != null, + name); readOccurrenceTypeInfo = readTypeInfo; } readKind = readTypeInfo.kind(); @@ -1266,7 +1282,8 @@ public JsonCreatorFieldInfo asCreatorField(int argumentIndex) { formatAnnotation, readUnboxedRequired, onNullRead, - onContentNullRead); + onContentNullRead, + lenientRead); } /** Assigns one already decoded value through this property's validated read sink. */ diff --git a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java index 62841c3262..da150c8007 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java @@ -23,6 +23,7 @@ import java.lang.invoke.MethodType; import java.math.BigDecimal; import java.math.BigInteger; +import java.math.RoundingMode; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; @@ -109,6 +110,9 @@ public abstract class JsonReader { 100_000_000_000_000_000L, 1_000_000_000_000_000_000L }; + private static final BigDecimal LONG_MIN_DECIMAL = BigDecimal.valueOf(Long.MIN_VALUE); + private static final BigDecimal LONG_MAX_DECIMAL = BigDecimal.valueOf(Long.MAX_VALUE); + private static final int LONG_MAX_DIGITS = 19; private static final int DOUBLE_FAST_MAX_SCALE = 15; private static final long DOUBLE_FAST_MAX_UNSCALED = 1L << 53; private static final int DOUBLE_FRACTION_BITS = 52; @@ -1199,6 +1203,161 @@ protected final void finishQuotedScalar() { throw error("Expected closing quote"); } + // Lenient property reads. These operations run only for properties whose metadata selected a + // lenient read codec, so strict readers never reach them. They use the representation-neutral + // cursor and leave native tokens to the concrete readers. + + /** + * Consumes the next value when it is an empty JSON string, or a string containing only JSON + * whitespace when {@code blank} is true. + * + * @return whether such a string was consumed; otherwise only leading whitespace is consumed + */ + @Internal + public final boolean tryReadEmptyString(boolean blank) { + skipWhitespace(); + if (position >= length() || charAt(position) != '"') { + return false; + } + int cursor = position + 1; + if (blank) { + cursor = scanWhitespace(cursor); + } + if (cursor < length() && charAt(cursor) == '"') { + position = cursor + 1; + return true; + } + return false; + } + + /** + * Consumes the opening quote and leading whitespace of a string whose unescaped content is a + * non-blank value with leading or trailing JSON whitespace. The caller then reads the bare token + * and finishes with {@link #finishPaddedQuotedScalar()}. + * + * @return whether the opening quote was consumed; otherwise only leading whitespace is consumed + */ + @Internal + public final boolean beginPaddedQuotedScalar() { + skipWhitespace(); + if (position >= length() || charAt(position) != '"') { + return false; + } + int contentStart = position + 1; + int close = contentStart; + int inputLength = length(); + while (close < inputLength) { + char ch = charAt(close); + if (ch == '"') { + break; + } + if (ch == '\\') { + return false; + } + close++; + } + if (close >= inputLength || close == contentStart) { + return false; + } + int tokenStart = scanWhitespace(contentStart); + if (tokenStart == close || tokenStart == contentStart && !isJsonWhitespace(charAt(close - 1))) { + return false; + } + position = tokenStart; + return true; + } + + /** + * Consumes trailing whitespace and the closing quote after {@link #beginPaddedQuotedScalar()}. + */ + @Internal + public final void finishPaddedQuotedScalar() { + skipWhitespace(); + finishQuotedScalar(); + } + + /** + * Reads a native or quoted JSON number as a {@code long}, truncating a fraction or exponent + * toward zero. An integral token uses the strict integer parser; values outside the {@code long} + * range fail. + */ + @Internal + public final long readTruncatedLong() { + skipWhitespace(); + boolean quoted = position < length() && charAt(position) == '"'; + if (quoted) { + beginQuotedScalar(); + } + int start = position; + long value; + if (scanNumberToken() == -1L) { + position = start; + value = readLongToken(); + } else { + BigDecimal decimal = truncatedDecimal(start, LONG_MAX_DIGITS, "Long overflow"); + if (decimal.compareTo(LONG_MIN_DECIMAL) < 0 || decimal.compareTo(LONG_MAX_DECIMAL) > 0) { + throw errorAt("Long overflow", start); + } + value = decimal.longValue(); + } + if (quoted) { + finishQuotedScalar(); + } + return value; + } + + /** + * Reads a native or quoted JSON number as a {@code BigInteger}, truncating a fraction or exponent + * toward zero. The integral part is limited to the arbitrary-precision number length. + */ + @Internal + public final BigInteger readTruncatedBigInteger() { + skipWhitespace(); + boolean quoted = position < length() && charAt(position) == '"'; + if (quoted) { + beginQuotedScalar(); + } + int start = position; + BigInteger value; + if (scanNumberToken() == -1L) { + position = start; + value = readBigIntegerToken(); + } else { + value = + truncatedDecimal(start, MAX_BIG_NUMBER_LENGTH, "Integer part is too long").toBigInteger(); + } + if (quoted) { + finishQuotedScalar(); + } + return value; + } + + // Parses the scanned token ending at the current position and drops its fraction. Magnitudes + // below one return zero before scaling, and the integral digit count is bounded before any + // exponent is expanded, so a huge exponent cannot drive allocation or work. + private BigDecimal truncatedDecimal(int start, int maxIntegerDigits, String overflow) { + if (position - start > MAX_BIG_NUMBER_LENGTH) { + throw errorAt("Number is too long", start); + } + BigDecimal decimal; + try { + decimal = new BigDecimal(slice(start, position)); + } catch (NumberFormatException e) { + throw errorAt("Number exponent is out of range", start); + } + if (decimal.signum() == 0 || decimal.abs().compareTo(BigDecimal.ONE) < 0) { + return BigDecimal.ZERO; + } + if ((long) decimal.precision() - decimal.scale() > maxIntegerDigits) { + throw errorAt(overflow, start); + } + return decimal.setScale(0, RoundingMode.DOWN); + } + + private static boolean isJsonWhitespace(char ch) { + return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'; + } + protected final BigDecimal readBigDecimalExponentValue( boolean negative, long unscaled, int scale, int exponentOffset) { int offset = exponentOffset + 1; diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/GeneratedCodecKeyBuilder.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/GeneratedCodecKeyBuilder.java index 5c24f5ee49..e736fcefae 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/GeneratedCodecKeyBuilder.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/GeneratedCodecKeyBuilder.java @@ -82,6 +82,7 @@ private GeneratedCodecKeyBuilder( keyParts.add(owner.failOnDuplicateProperties()); keyParts.add(registry.onNullRead()); keyParts.add(registry.onContentNullRead()); + keyParts.add(registry.lenientRead()); } // Both readers and writers store concrete byte-array codecs selected by this default. keyParts.add(registry.byteArrayFormat()); @@ -183,12 +184,14 @@ private void addOccurrences() { for (JsonFieldInfo field : owner.readFields()) { keyParts.add(field.onNullRead()); keyParts.add(field.onContentNullRead()); + keyParts.add(field.lenientRead()); addRegistration(field.readTypeInfo()); } } else { for (JsonCreatorFieldInfo field : creator.fields()) { keyParts.add(field.onNullRead()); keyParts.add(field.onContentNullRead()); + keyParts.add(field.lenientRead()); addRegistration(field.typeInfo()); } } @@ -201,6 +204,10 @@ private void addOccurrences() { route.field() == null ? route.creatorField().onContentNullRead() : route.field().onContentNullRead()); + keyParts.add( + route.field() == null + ? route.creatorField().lenientRead() + : route.field().lenientRead()); addRegistration( route.field() == null ? route.creatorField().typeInfo() : route.field().readTypeInfo()); } diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonMixinAnnotations.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonMixinAnnotations.java index 35f051325e..9d24ddefbc 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonMixinAnnotations.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonMixinAnnotations.java @@ -52,6 +52,7 @@ import org.apache.fory.json.annotation.JsonFormat; import org.apache.fory.json.annotation.JsonIgnore; import org.apache.fory.json.annotation.JsonInclude; +import org.apache.fory.json.annotation.JsonLenient; import org.apache.fory.json.annotation.JsonMixin; import org.apache.fory.json.annotation.JsonMixinRemove; import org.apache.fory.json.annotation.JsonProperty; @@ -78,6 +79,7 @@ final class JsonMixinAnnotations { JsonFormat.class, JsonIgnore.class, JsonInclude.class, + JsonLenient.class, JsonProperty.class, JsonPropertyOrder.class, JsonRawValue.class, diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonSharedRegistry.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonSharedRegistry.java index fda8df6efd..3cf08e3ac7 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonSharedRegistry.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonSharedRegistry.java @@ -119,6 +119,7 @@ import org.apache.fory.json.codec.GuavaCodecs; import org.apache.fory.json.codec.JsonSubTypesInfo; import org.apache.fory.json.codec.JsonValueCodec; +import org.apache.fory.json.codec.LenientReadCodec; import org.apache.fory.json.codec.MapCodec; import org.apache.fory.json.codec.MapKeyCodec; import org.apache.fory.json.codec.ObjectCodec; @@ -196,6 +197,7 @@ public int compare(DeclarationCandidate left, DeclarationCandidate right) { private final boolean escapeNonAscii; private final boolean failOnMissingRequiredProperties; private final boolean failOnDuplicateProperties; + private final int lenientRead; private final JsonByteArray.Format byteArrayFormat; private final ClassLoader classLoader; private final JsonMixinAnnotations mixinAnnotations; @@ -258,6 +260,7 @@ private JsonSharedRegistry( escapeNonAscii = config.escapeNonAscii(); failOnMissingRequiredProperties = config.failOnMissingRequiredProperties(); failOnDuplicateProperties = config.failOnDuplicateProperties(); + lenientRead = LenientReadCodec.mask(config.lenientRead()); byteArrayFormat = config.byteArrayFormat(); classLoader = config.classLoader(); mixinAnnotations = new JsonMixinAnnotations(config); @@ -1250,6 +1253,11 @@ public boolean failOnDuplicateProperties() { return failOnDuplicateProperties; } + /** Returns the builder's lenient read feature mask for properties without a declaration. */ + public int lenientRead() { + return lenientRead; + } + /** Returns the default representation used when selecting ordinary byte-array codecs. */ @Internal public JsonByteArray.Format byteArrayFormat() { diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java index d9873982f1..6f82b2c37e 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java @@ -62,6 +62,7 @@ import org.apache.fory.json.codec.JsonUnwrappedInfo; import org.apache.fory.json.codec.JsonValueCodec; import org.apache.fory.json.codec.Latin1ReaderCodec; +import org.apache.fory.json.codec.LenientReadCodec; import org.apache.fory.json.codec.MapCodec; import org.apache.fory.json.codec.MapKeyCodec; import org.apache.fory.json.codec.ObjectCodec; @@ -505,6 +506,77 @@ public JsonTypeInfo withContentNullRead(JsonTypeInfo typeInfo, NullHandling hand return occurrence; } + /** + * Resolves the read occurrence of a property with lenient features. Features apply only to + * Fory-owned representations; {@code typeInfo} is {@code null} and {@code selected} is true when + * the property selects its own representation. The occurrence is returned unchanged when no + * feature fits, which is rejected for a feature set declared on the property itself. + */ + @Internal + public JsonTypeInfo withLenientRead( + JsonTypeInfo typeInfo, int lenientRead, boolean selected, String property) { + int features = lenientRead & LenientReadCodec.FEATURES; + if (features == 0) { + return typeInfo; + } + boolean declared = (lenientRead & LenientReadCodec.DECLARED) != 0; + if (typeInfo == null || selected) { + if (declared) { + throw new ForyJsonException( + "@JsonLenient requires the default representation of JSON property " + property); + } + return typeInfo; + } + JsonTypeInfo lenient = lenientTypeInfo(typeInfo, features); + if (lenient == typeInfo && declared) { + throw new ForyJsonException( + "@JsonLenient has no feature applicable to JSON property " + + property + + " of type " + + typeInfo.type()); + } + return lenient; + } + + private JsonTypeInfo lenientTypeInfo(JsonTypeInfo typeInfo, int features) { + LenientReadCodec scalar = LenientReadCodec.scalar(typeInfo, features); + if (scalar != null) { + return newTypeInfo(typeInfo.typeRef(), JsonFieldKind.OBJECT, scalar, true); + } + JsonValueCodec codec = typeInfo.valueCodec(); + JsonTypeInfo occurrence = typeInfo; + JsonTypeInfo element = null; + if (codec instanceof ArrayCodec || codec instanceof CollectionCodec) { + TypeRef typeRef = typeInfo.typeRef(); + Class rawType = typeInfo.rawType(); + TypeRef elementType = + rawType.isArray() ? typeRef.getComponentType() : CodecUtils.elementTypeRef(typeRef); + element = getTypeInfo(elementType); + LenientReadCodec elementCodec = LenientReadCodec.scalar(element, features); + if (elementCodec != null) { + // Rebuild only this occurrence with lenient direct elements. The shared element and + // container bindings stay strict, and the occurrence keeps its content null handling. + element = newTypeInfo(elementType, JsonFieldKind.OBJECT, elementCodec, true); + NullHandling handling; + JsonValueCodec rebuilt; + if (codec instanceof ArrayCodec) { + handling = ((ArrayCodec) codec).onContentNullRead(); + rebuilt = ArrayCodec.create(rawType, element, sharedRegistry.byteArrayFormat()); + } else { + handling = ((CollectionCodec) codec).onContentNullRead(); + rebuilt = CollectionCodec.create(rawType, elementType.getRawType(), element, this); + } + occurrence = newTypeInfo(typeRef, rebuilt); + registerTypeInfoOwner(occurrence, rebuilt); + occurrence = withContentNullRead(occurrence, handling); + } + } + LenientReadCodec container = LenientReadCodec.container(occurrence, element, features); + return container == null + ? occurrence + : newTypeInfo(typeInfo.typeRef(), JsonFieldKind.OBJECT, container, true); + } + /** Generates hosted capabilities and returns their language-neutral object metadata owners. */ @Internal public List> generateHostedCodecs(Class type) { diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonAsyncCompilationTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonAsyncCompilationTest.java index 7f38158395..0ac463e733 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonAsyncCompilationTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonAsyncCompilationTest.java @@ -61,6 +61,7 @@ import org.apache.fory.json.annotation.JsonByteArray; import org.apache.fory.json.annotation.JsonCodec; import org.apache.fory.json.annotation.JsonCreator; +import org.apache.fory.json.annotation.JsonLenient; import org.apache.fory.json.annotation.JsonProperty.Include; import org.apache.fory.json.annotation.JsonProperty.NullHandling; import org.apache.fory.json.annotation.JsonSubTypes; @@ -1454,6 +1455,7 @@ private static ControlledJson controlledJson( false, failOnMissingRequiredProperties, false, + Collections.emptySet(), JsonByteArray.Format.BASE64, true, true, diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonCreatorTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonCreatorTest.java index 6c46ca2615..7f6ff8dad1 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonCreatorTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonCreatorTest.java @@ -138,7 +138,8 @@ public void deferredTransparentNullCarrierResolution() throws Exception { null, true, NullHandling.SET, - NullHandling.DEFAULT); + NullHandling.DEFAULT, + 0); JsonCreatorInfo creator = new JsonCreatorInfo( DeferredCarrierOwner.class, diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java new file mode 100644 index 0000000000..64b0240b6e --- /dev/null +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -0,0 +1,377 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fory.json; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.expectThrows; + +import java.io.ByteArrayInputStream; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.apache.fory.json.annotation.JsonCreator; +import org.apache.fory.json.annotation.JsonFormat; +import org.apache.fory.json.annotation.JsonLenient; +import org.apache.fory.json.annotation.JsonLenient.Feature; +import org.apache.fory.json.annotation.JsonMixin; +import org.apache.fory.json.annotation.JsonProperty; +import org.apache.fory.json.annotation.JsonProperty.NullHandling; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; + +public class JsonLenientTest extends ForyJsonTestModels { + private static final int REPRESENTATIONS = 4; + + @Factory(dataProvider = "enableCodegen") + public JsonLenientTest(boolean codegen) { + super(codegen); + } + + public static class Banner { + public int w; + } + + public static class Imp { + public String id; + public List cat; + public String[] tags; + public int w; + public Integer h; + public long l; + public Long boxedLong; + public short s; + public byte b; + public BigInteger big; + public double d; + public Double boxedDouble; + public BigDecimal decimal; + public boolean flag; + public Boolean boxedFlag; + public Banner banner; + public List banners; + public Map ext; + public List nums; + public int[] sizes; + public Set ids; + } + + @JsonLenient + public static class LenientImp extends Imp {} + + @JsonLenient + public static class PartlyStrict { + public List cat; + + @JsonLenient({}) + public List strictCat; + + @JsonLenient(Feature.SCALAR_AS_STRING) + public String id; + } + + public static class PropertyOnly { + @JsonLenient(Feature.SINGLE_VALUE_AS_ARRAY) + public List cat; + + public List strictCat; + private int w; + + public int getW() { + return w; + } + + @JsonLenient(Feature.FLOAT_AS_INT) + public void setW(int w) { + this.w = w; + } + } + + public static final class CreatorImp { + private final List cat; + private final int w; + + @JsonCreator + public CreatorImp( + @JsonLenient @JsonProperty("cat") List cat, + @JsonLenient(Feature.FLOAT_AS_INT) @JsonProperty("w") int w) { + this.cat = cat; + this.w = w; + } + } + + @JsonLenient + public static class Defaults { + public Integer h = 5; + public List cat = Collections.singletonList("default"); + } + + @JsonLenient({}) + public static class StrictImp { + public int w; + } + + public static class MixinTarget { + public List cat; + } + + public static class WrongFeature { + @JsonLenient(Feature.SINGLE_VALUE_AS_ARRAY) + public String id; + } + + public static class WithFormat { + @JsonLenient + @JsonFormat(shape = JsonFormat.Shape.STRING) + public int w; + } + + public static class ConflictingDeclarations { + @JsonLenient(Feature.FLOAT_AS_INT) + private int w; + + public int getW() { + return w; + } + + @JsonLenient(Feature.EMPTY_STRING_AS_NULL) + public void setW(int w) { + this.w = w; + } + } + + private static T read(ForyJson json, String text, Class type, int representation) { + switch (representation) { + case 0: + return json.fromJson(text, type); + case 1: + // A trailing unknown member makes the input UTF-16 while known members keep their order. + return json.fromJson( + text.substring(0, text.length() - 1) + ",\"ignoredUnicode\":\"中\"}", type); + case 2: + return json.fromJson(text.getBytes(StandardCharsets.UTF_8), type); + default: + return json.fromJson(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)), type); + } + } + + private static void assertRejected(ForyJson json, String text, Class type, String message) { + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + int current = representation; + ForyJsonException error = + expectThrows(ForyJsonException.class, () -> read(json, text, type, current)); + assertTrue(String.valueOf(error.getMessage()).contains(message), error.getMessage()); + } + } + + @Test + public void strictByDefault() { + ForyJson json = newJson(); + assertRejected(json, "{\"cat\":\"IAB1\"}", Imp.class, ""); + assertRejected(json, "{\"id\":123}", Imp.class, ""); + assertRejected(json, "{\"w\":300.7}", Imp.class, ""); + assertRejected(json, "{\"w\":\" 300 \"}", Imp.class, ""); + assertRejected(json, "{\"h\":\"\"}", Imp.class, ""); + assertRejected(json, "{\"banner\":\"\"}", Imp.class, ""); + } + + @Test + public void offSpecShapes() { + ForyJson json = newJson(); + String text = + "{\"id\":-1.50e3,\"cat\":\"IAB1\",\"tags\":\"t\",\"w\":300.7,\"h\":\" 250 \"," + + "\"l\":\"-9.9e1\",\"boxedLong\":1e3,\"s\":\" 7.9 \",\"b\":-1.5," + + "\"big\":12345678901234567890.99,\"d\":\" 1.5 \",\"boxedDouble\":\"\"," + + "\"decimal\":\" 2.50 \",\"flag\":\" true \",\"boxedFlag\":\"\"," + + "\"banner\":\"\",\"banners\":{\"w\":5},\"ext\":\"\",\"nums\":\" 3.5 \"," + + "\"sizes\":[1.5,\" 2 \"],\"ids\":7}"; + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + LenientImp imp = read(json, text, LenientImp.class, representation); + assertEquals(imp.id, "-1.50e3"); + assertEquals(imp.cat, Collections.singletonList("IAB1")); + assertEquals(imp.tags, new String[] {"t"}); + assertEquals(imp.w, 300); + assertEquals(imp.h, Integer.valueOf(250)); + assertEquals(imp.l, -99L); + assertEquals(imp.boxedLong, Long.valueOf(1000L)); + assertEquals(imp.s, (short) 7); + assertEquals(imp.b, (byte) -1); + assertEquals(imp.big, new BigInteger("12345678901234567890")); + assertEquals(imp.d, 1.5d); + assertNull(imp.boxedDouble); + assertEquals(imp.decimal, new BigDecimal("2.50")); + assertTrue(imp.flag); + assertNull(imp.boxedFlag); + assertNull(imp.banner); + assertEquals(imp.banners.size(), 1); + assertEquals(imp.banners.get(0).w, 5); + assertNull(imp.ext); + assertEquals(imp.nums, Collections.singletonList(3)); + assertEquals(imp.sizes, new int[] {1, 2}); + assertEquals(imp.ids, Collections.singleton(7L)); + } + assertGeneratedWhenSupported(json, LenientImp.class); + } + + @Test + public void emptyStrings() { + ForyJson json = newJson(); + String text = + "{\"id\":\"\",\"cat\":\"\",\"w\":\"\",\"h\":\" \",\"flag\":\"\",\"d\":\"\"," + + "\"nums\":[\"\",1],\"sizes\":\"\"}"; + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + LenientImp imp = read(json, text, LenientImp.class, representation); + assertEquals(imp.id, ""); + assertNull(imp.cat); + assertEquals(imp.w, 0); + assertNull(imp.h); + assertFalse(imp.flag); + assertEquals(imp.d, 0d); + assertEquals(imp.nums, Arrays.asList(null, 1)); + assertNull(imp.sizes); + } + } + + @Test + public void nativeShapesUnchanged() { + ForyJson lenient = newJson(); + ForyJson strict = newJson(); + String text = + "{\"id\":\"a\",\"cat\":[\"x\",\"y\"],\"tags\":[],\"w\":3,\"h\":null,\"l\":\"4\"," + + "\"boxedLong\":null,\"s\":5,\"b\":6,\"big\":\"7\",\"d\":1.25,\"boxedDouble\":\"NaN\"," + + "\"decimal\":\"1.10\",\"flag\":\"true\",\"boxedFlag\":false,\"banner\":{\"w\":8}," + + "\"banners\":[],\"ext\":{\"k\":9},\"nums\":[1,null],\"sizes\":[2],\"ids\":null}"; + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + LenientImp imp = read(lenient, text, LenientImp.class, representation); + Imp expected = read(strict, text, Imp.class, representation); + assertEquals(lenient.toJson(imp), strict.toJson(expected)); + } + } + + @Test + public void truncationLimits() { + ForyJson json = newJson(); + assertRejected(json, "{\"w\":3e10}", LenientImp.class, "Integer overflow"); + assertRejected(json, "{\"b\":128.5}", LenientImp.class, "Byte overflow"); + assertRejected(json, "{\"l\":1e999999999}", LenientImp.class, "Long overflow"); + assertRejected(json, "{\"big\":1e20000}", LenientImp.class, "Integer part is too long"); + assertRejected(json, "{\"l\":1e9999999999}", LenientImp.class, "exponent is out of range"); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + LenientImp imp = + read( + json, + "{\"l\":1e-999999999,\"big\":-0.5,\"w\":-0.0}", + LenientImp.class, + representation); + assertEquals(imp.l, 0L); + assertEquals(imp.big, BigInteger.ZERO); + assertEquals(imp.w, 0); + } + } + + @Test + public void malformedPaddedScalars() { + ForyJson json = newJson(); + assertRejected(json, "{\"w\":\" 30 0 \"}", LenientImp.class, ""); + assertRejected(json, "{\"h\":\" null \"}", LenientImp.class, ""); + assertRejected(json, "{\"h\":\" \\\"1\\\" \"}", LenientImp.class, ""); + } + + @Test + public void propertyAndClassSettings() { + ForyJson json = newJson(); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + PartlyStrict partly = + read( + json, + "{\"cat\":\"a\",\"strictCat\":[\"b\"],\"id\":5}", + PartlyStrict.class, + representation); + assertEquals(partly.cat, Collections.singletonList("a")); + assertEquals(partly.strictCat, Collections.singletonList("b")); + assertEquals(partly.id, "5"); + PropertyOnly property = + read(json, "{\"cat\":\"a\",\"w\":2.5}", PropertyOnly.class, representation); + assertEquals(property.cat, Collections.singletonList("a")); + assertEquals(property.getW(), 2); + CreatorImp creator = + read(json, "{\"cat\":\"a\",\"w\":3.5}", CreatorImp.class, representation); + assertEquals(creator.cat, Collections.singletonList("a")); + assertEquals(creator.w, 3); + } + assertRejected(json, "{\"strictCat\":\"b\"}", PartlyStrict.class, ""); + assertRejected(json, "{\"strictCat\":\"b\"}", PropertyOnly.class, ""); + assertRejected(json, "{\"w\":\"\"}", PropertyOnly.class, ""); + assertGeneratedWhenSupported(json, PartlyStrict.class); + assertGeneratedWhenSupported(json, PropertyOnly.class); + } + + @Test + public void builderDefault() { + ForyJson json = newJsonBuilder().lenientRead(Feature.FLOAT_AS_INT).build(); + assertEquals(json.config().lenientRead(), Collections.singleton(Feature.FLOAT_AS_INT)); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + assertEquals(read(json, "{\"w\":2.5}", Imp.class, representation).w, 2); + } + assertRejected(json, "{\"w\":\" 2 \"}", Imp.class, ""); + assertRejected(json, "{\"w\":2.5}", StrictImp.class, ""); + // Root values are outside property metadata. + expectThrows(ForyJsonException.class, () -> json.fromJson("2.5", int.class)); + } + + @Test + public void mixinSuppliesClassSetting() { + ForyJson json = newJsonBuilder().registerMixin(Mixin.class).build(); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + assertEquals( + read(json, "{\"cat\":\"a\"}", MixinTarget.class, representation).cat, + Collections.singletonList("a")); + } + } + + @JsonMixin(target = MixinTarget.class) + @JsonLenient(Feature.SINGLE_VALUE_AS_ARRAY) + public abstract static class Mixin {} + + @Test + public void invalidDeclarations() { + ForyJson json = newJson(); + assertRejected(json, "{\"id\":\"a\"}", WrongFeature.class, "no feature applicable"); + assertRejected(json, "{\"w\":1}", WithFormat.class, "requires the default representation"); + assertRejected(json, "{\"w\":1}", ConflictingDeclarations.class, "Conflicting @JsonLenient"); + } + + @Test + public void emptyStringIsNotExplicitNull() { + ForyJson json = newJsonBuilder().onNullRead(NullHandling.SKIP).build(); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + Defaults defaults = read(json, "{\"h\":\"\",\"cat\":null}", Defaults.class, representation); + assertNull(defaults.h); + assertEquals(defaults.cat, Collections.singletonList("default")); + } + } +} diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonTestSupport.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonTestSupport.java index 8887d81c06..1fe1f00a54 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonTestSupport.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonTestSupport.java @@ -27,6 +27,7 @@ import java.util.Collections; import java.util.Map; import org.apache.fory.json.annotation.JsonByteArray; +import org.apache.fory.json.annotation.JsonLenient; import org.apache.fory.json.annotation.JsonProperty.Include; import org.apache.fory.json.annotation.JsonProperty.NullHandling; import org.apache.fory.json.codec.JsonValueCodec; @@ -52,6 +53,7 @@ final class JsonTestSupport { false, false, false, + Collections.emptySet(), JsonByteArray.Format.BASE64, false, false, From 18f0ab69befe6d5473285fcf9844350669c248e6 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 16:25:33 +0100 Subject: [PATCH 02/15] fix(java): keep lenient JSON reads within non-null and string rules Reject an empty string decoded to null for a non-null occurrence and a null single element for a non-null array, limit lenient quote padding to spaces, and reject @JsonLenient on a property that is never read. Add tests for element-only leniency, single values into primitive and byte arrays, class settings on creator parameters, and invalid placements. Co-Authored-By: Claude Opus 5.5 --- docs/json/annotations.md | 12 +- .../fory/json/annotation/JsonLenient.java | 5 +- .../fory/json/codec/LenientReadCodec.java | 23 +++- .../fory/json/codec/ObjectCodecBuilder.java | 4 + .../apache/fory/json/reader/JsonReader.java | 32 ++++-- .../org/apache/fory/json/JsonLenientTest.java | 104 ++++++++++++++++++ 6 files changed, 155 insertions(+), 25 deletions(-) diff --git a/docs/json/annotations.md b/docs/json/annotations.md index 7405d8bae8..cc0bc23cdb 100644 --- a/docs/json/annotations.md +++ b/docs/json/annotations.md @@ -384,7 +384,7 @@ independent; the annotation without arguments enables all of them: | `SINGLE_VALUE_AS_ARRAY` | a value other than an array or `null` as a one-element array, for example `"IAB1"` | arrays (except binary-encoded `byte[]`) and collections | | `SCALAR_AS_STRING` | a number or boolean as its exact token text, for example `1.50` as `"1.50"` | `String` | | `FLOAT_AS_INT` | a number with a fraction or exponent, truncated toward zero: `300.7` as `300`, `1e3` | `byte`, `short`, `int`, `long`, their boxed types, and `BigInteger` | -| `TRIM_QUOTED_SCALAR` | a quoted boolean or number with surrounding whitespace, for example `" 300 "` | boolean and numeric types | +| `TRIM_QUOTED_SCALAR` | a quoted boolean or number with surrounding spaces, for example `" 300 "` | boolean and numeric types | | `EMPTY_STRING_AS_NULL` | `""` as `null`; primitives receive `false` or zero | boolean, numeric, object, map, array, and collection types | ```java @@ -419,14 +419,14 @@ property-owned array or collection, so `["1", 2.9, ""]` read into `List is `[1, 2, null]`. They apply only where Fory owns the representation: properties with `JsonCodec`, `JsonFormat`, `JsonByteArray`, a registered codec, or a `JsonValue` type keep their representation. A class or builder setting applies silently wherever a feature fits the property type. A property -declaration with no feature that fits the property type, or one on a property that selects its own -representation, an Any member, or an unwrapped property, is rejected when the class metadata is -built. +declaration with no feature that fits the property type, or one on a property that is never read, +selects its own representation, is an Any member, or is unwrapped, is rejected when the class +metadata is built. Additional rules: -- Truncation still fails for values outside the target range. `TRIM_QUOTED_SCALAR` does not accept - escape sequences or anything other than one token between the whitespace. +- Truncation still fails for values outside the target range. `TRIM_QUOTED_SCALAR` accepts only + spaces around exactly one token: escape sequences and other characters still fail. - An empty string read into an array or collection is `null`, not a one-element array. - An empty string is a decoded value, not an explicit JSON null, so `JsonProperty.onNullRead` does not apply to it. diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java index 69726e9122..38bca21049 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java @@ -79,13 +79,14 @@ enum Feature { FLOAT_AS_INT, /** * A quoted boolean or number read into a boolean or numeric target may have leading and - * trailing JSON whitespace inside the quotes, for example {@code " 300 "}. + * trailing spaces inside the quotes, for example {@code " 300 "}. Escapes and other characters + * around the value are not accepted. */ TRIM_QUOTED_SCALAR, /** * An empty JSON string read into a boolean, numeric, object, map, array, or collection target * is read as {@code null}; primitive targets receive {@code false} or zero. With {@link - * #TRIM_QUOTED_SCALAR}, a whitespace-only string read into a boolean or numeric target is also + * #TRIM_QUOTED_SCALAR}, a space-only string read into a boolean or numeric target is also * empty. The value is assigned like any other decoded value: explicit-null handling does not * apply. Text targets such as strings, enums, and date/time values are not affected. */ diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java index d0da70a3d2..dc2341a1f4 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java @@ -171,6 +171,14 @@ public static LenientReadCodec container(JsonTypeInfo base, JsonTypeInfo element : new ContainerCodec(base, element, containerFeatures); } + // An empty string decodes to null, which a non-null occurrence rejects like a JSON null token. + final Object emptyReference() { + if (base.rejectsNull()) { + base.rejectNullValue(); + } + return null; + } + @Override public final void writeString(StringJsonWriter writer, Object value) { base.stringWriter().writeString(writer, value); @@ -303,7 +311,7 @@ private Object finish(JsonReader reader, Object opening, Object value) { public Object readLatin1(Latin1JsonReader reader) { Object opening = begin(reader); if (opening != NATIVE && opening != PADDED) { - return opening == EMPTY_REFERENCE ? null : opening; + return opening == EMPTY_REFERENCE ? emptyReference() : opening; } Object value = truncate ? readTruncated(reader) : NATIVE; if (value == NATIVE) { @@ -316,7 +324,7 @@ public Object readLatin1(Latin1JsonReader reader) { public Object readUtf16(Utf16JsonReader reader) { Object opening = begin(reader); if (opening != NATIVE && opening != PADDED) { - return opening == EMPTY_REFERENCE ? null : opening; + return opening == EMPTY_REFERENCE ? emptyReference() : opening; } Object value = truncate ? readTruncated(reader) : NATIVE; if (value == NATIVE) { @@ -329,7 +337,7 @@ public Object readUtf16(Utf16JsonReader reader) { public Object readUtf8(Utf8JsonReader reader) { Object opening = begin(reader); if (opening != NATIVE && opening != PADDED) { - return opening == EMPTY_REFERENCE ? null : opening; + return opening == EMPTY_REFERENCE ? emptyReference() : opening; } Object value = truncate ? readTruncated(reader) : NATIVE; if (value == NATIVE) { @@ -373,7 +381,7 @@ Object single(JsonReader reader, Object value) { public final Object readLatin1(Latin1JsonReader reader) { switch (shape(reader)) { case EMPTY: - return null; + return emptyReference(); case SINGLE: return single(reader, element.latin1Reader().readLatin1(reader)); default: @@ -385,7 +393,7 @@ public final Object readLatin1(Latin1JsonReader reader) { public final Object readUtf16(Utf16JsonReader reader) { switch (shape(reader)) { case EMPTY: - return null; + return emptyReference(); case SINGLE: return single(reader, element.utf16Reader().readUtf16(reader)); default: @@ -397,7 +405,7 @@ public final Object readUtf16(Utf16JsonReader reader) { public final Object readUtf8(Utf8JsonReader reader) { switch (shape(reader)) { case EMPTY: - return null; + return emptyReference(); case SINGLE: return single(reader, element.utf8Reader().readUtf8(reader)); default: @@ -418,6 +426,9 @@ private ArrayElementCodec( @Override Object single(JsonReader reader, Object value) { + if (value == null && element.rejectsNull()) { + element.rejectNullValue(); + } return ArrayCodec.singleElementArray(reader, componentType, value); } } diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java index 02dde2b928..930c95c82a 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java @@ -3411,6 +3411,10 @@ private JsonFieldInfo build( GeneratedJsonCodec generatedCodec, boolean escapeNonAscii) { validateTypes(ownerType); + if (lenientAnnotation != null && !hasReadSink() && creatorArgumentIndex < 0) { + throw new ForyJsonException( + "@JsonLenient requires a read-enabled property: " + name + " from " + lenientSource); + } if (explicitInclude != JsonProperty.Include.DEFAULT && !hasWriteSource()) { throw new ForyJsonException( "JSON inclusion policy requires a write source for property " + name); diff --git a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java index da150c8007..522a3688fb 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java @@ -1208,8 +1208,8 @@ protected final void finishQuotedScalar() { // cursor and leave native tokens to the concrete readers. /** - * Consumes the next value when it is an empty JSON string, or a string containing only JSON - * whitespace when {@code blank} is true. + * Consumes the next value when it is an empty JSON string, or a string containing only spaces + * when {@code blank} is true. * * @return whether such a string was consumed; otherwise only leading whitespace is consumed */ @@ -1221,7 +1221,7 @@ public final boolean tryReadEmptyString(boolean blank) { } int cursor = position + 1; if (blank) { - cursor = scanWhitespace(cursor); + cursor = scanSpaces(cursor); } if (cursor < length() && charAt(cursor) == '"') { position = cursor + 1; @@ -1232,8 +1232,8 @@ public final boolean tryReadEmptyString(boolean blank) { /** * Consumes the opening quote and leading whitespace of a string whose unescaped content is a - * non-blank value with leading or trailing JSON whitespace. The caller then reads the bare token - * and finishes with {@link #finishPaddedQuotedScalar()}. + * non-blank value with leading or trailing spaces. The caller then reads the bare token and + * finishes with {@link #finishPaddedQuotedScalar()}. * * @return whether the opening quote was consumed; otherwise only leading whitespace is consumed */ @@ -1259,20 +1259,20 @@ public final boolean beginPaddedQuotedScalar() { if (close >= inputLength || close == contentStart) { return false; } - int tokenStart = scanWhitespace(contentStart); - if (tokenStart == close || tokenStart == contentStart && !isJsonWhitespace(charAt(close - 1))) { + int tokenStart = scanSpaces(contentStart); + if (tokenStart == close + || tokenStart == contentStart && charAt(close - 1) != ' ' + || isJsonWhitespace(charAt(tokenStart))) { return false; } position = tokenStart; return true; } - /** - * Consumes trailing whitespace and the closing quote after {@link #beginPaddedQuotedScalar()}. - */ + /** Consumes trailing spaces and the closing quote after {@link #beginPaddedQuotedScalar()}. */ @Internal public final void finishPaddedQuotedScalar() { - skipWhitespace(); + position = scanSpaces(position); finishQuotedScalar(); } @@ -1354,6 +1354,16 @@ private BigDecimal truncatedDecimal(int start, int maxIntegerDigits, String over return decimal.setScale(0, RoundingMode.DOWN); } + // String content may contain raw spaces but no raw control characters, so lenient padding inside + // quotes is limited to spaces. + private int scanSpaces(int cursor) { + int inputLength = length(); + while (cursor < inputLength && charAt(cursor) == ' ') { + cursor++; + } + return cursor; + } + private static boolean isJsonWhitespace(char ch) { return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'; } diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java index 64b0240b6e..7e651dc8e7 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -34,6 +34,8 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.fory.json.annotation.JsonAnyProperty; +import org.apache.fory.json.annotation.JsonByteArray; import org.apache.fory.json.annotation.JsonCreator; import org.apache.fory.json.annotation.JsonFormat; import org.apache.fory.json.annotation.JsonLenient; @@ -41,6 +43,13 @@ import org.apache.fory.json.annotation.JsonMixin; import org.apache.fory.json.annotation.JsonProperty; import org.apache.fory.json.annotation.JsonProperty.NullHandling; +import org.apache.fory.json.annotation.JsonUnwrapped; +import org.apache.fory.json.codec.LenientReadCodec; +import org.apache.fory.json.resolver.JsonTypeInfo; +import org.apache.fory.json.resolver.JsonTypeResolver; +import org.apache.fory.meta.TypeExtMeta; +import org.apache.fory.reflect.TypeRef; +import org.apache.fory.type.Types; import org.testng.annotations.Factory; import org.testng.annotations.Test; @@ -78,6 +87,7 @@ public static class Imp { public List nums; public int[] sizes; public Set ids; + public byte[] data; } @JsonLenient @@ -130,6 +140,32 @@ public static class Defaults { public List cat = Collections.singletonList("default"); } + @JsonLenient + public static final class LenientCreator { + private final int w; + + @JsonCreator + public LenientCreator(@JsonProperty("w") int w) { + this.w = w; + } + } + + public static class WriteOnly { + @JsonLenient + public int getW() { + return 1; + } + } + + public static class LenientUnwrapped { + @JsonLenient @JsonUnwrapped public Banner banner; + } + + public static class LenientAny { + public int id; + @JsonLenient @JsonAnyProperty public Map values; + } + @JsonLenient({}) public static class StrictImp { public int w; @@ -363,6 +399,74 @@ public void invalidDeclarations() { assertRejected(json, "{\"id\":\"a\"}", WrongFeature.class, "no feature applicable"); assertRejected(json, "{\"w\":1}", WithFormat.class, "requires the default representation"); assertRejected(json, "{\"w\":1}", ConflictingDeclarations.class, "Conflicting @JsonLenient"); + assertRejected(json, "{}", WriteOnly.class, "requires a read-enabled property"); + assertRejected(json, "{}", LenientUnwrapped.class, "@JsonUnwrapped"); + assertRejected(json, "{\"id\":1}", LenientAny.class, "JSON Any"); + } + + @Test + public void controlCharactersAreNotPadding() { + ForyJson json = newJson(); + assertRejected(json, "{\"w\":\"\n300\"}", LenientImp.class, ""); + assertRejected(json, "{\"w\":\"300\t\"}", LenientImp.class, ""); + assertRejected(json, "{\"w\":\"\\n300\"}", LenientImp.class, ""); + assertRejected(json, "{\"h\":\"\t\"}", LenientImp.class, ""); + } + + @Test + public void elementsAndSingleValues() { + ForyJson json = newJsonBuilder().lenientRead(Feature.FLOAT_AS_INT).build(); + ForyJson all = newJson(); + ForyJson byteArrays = newJsonBuilder().byteArrayFormat(JsonByteArray.Format.ARRAY).build(); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + Imp imp = read(json, "{\"nums\":[1.5,-2.5],\"sizes\":[2.7]}", Imp.class, representation); + assertEquals(imp.nums, Arrays.asList(1, -2)); + assertEquals(imp.sizes, new int[] {2}); + LenientImp lenient = + read(all, "{\"sizes\":5,\"data\":\"AQI=\"}", LenientImp.class, representation); + assertEquals(lenient.sizes, new int[] {5}); + assertEquals(lenient.data, new byte[] {1, 2}); + lenient = read(byteArrays, "{\"data\":7}", LenientImp.class, representation); + assertEquals(lenient.data, new byte[] {7}); + lenient = read(byteArrays, "{\"data\":[1.5,\" 2 \"]}", LenientImp.class, representation); + assertEquals(lenient.data, new byte[] {1, 2}); + assertEquals(read(all, "{\"w\":4.5}", LenientCreator.class, representation).w, 4); + } + assertRejected(json, "{\"nums\":\"1\"}", Imp.class, ""); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + assertEquals( + read(all, "{\"sizes\":[\"\"]}", LenientImp.class, representation).sizes, new int[] {0}); + } + } + + @Test + public void nonNullOccurrence() { + ForyJson json = newJson(); + JsonTypeResolver resolver = JsonTestSupport.currentTypeResolver(json); + int features = LenientReadCodec.mask(Arrays.asList(Feature.values())); + for (Class type : new Class[] {Integer.class, Banner.class, List.class}) { + JsonTypeInfo typeInfo; + resolver.lockJIT(); + try { + typeInfo = + resolver.withLenientRead( + resolver.getTypeInfo( + TypeRef.of(type, TypeExtMeta.of(Types.UNKNOWN, false, false, false, false))), + features, + false, + "value"); + } finally { + resolver.unlockJIT(); + } + ForyJsonException error = + expectThrows( + ForyJsonException.class, + () -> + typeInfo + .utf8Reader() + .readUtf8(JsonTestSupport.newUtf8Reader(new byte[] {'"', '"'}))); + assertTrue(error.getMessage().contains("JSON null is not allowed"), error.getMessage()); + } } @Test From 2dea2598f2af820ce756878563afdaeace85961f Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 16:33:40 +0100 Subject: [PATCH 03/15] fix(java): keep module-owned JSON array representations strict under leniency Rebuild lenient array elements only when the array uses the default representation of its component, and read collection single values with the collection's own element type information, so module carriers such as unsigned arrays keep their semantics. Co-Authored-By: Claude Opus 5.5 --- .../fory/json/codec/CollectionCodec.java | 6 +++++ .../fory/json/resolver/JsonTypeResolver.java | 17 +++++++++++--- .../org/apache/fory/json/JsonLenientTest.java | 23 +++++++++++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) 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 41fe0eb060..8f03a6c057 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 @@ -318,6 +318,12 @@ public final boolean createsArrayList() { return createsArrayList; } + /** Returns the element type information this collection reads its elements with. */ + @Internal + public final JsonTypeInfo elementTypeInfo() { + return elementTypeInfo; + } + /** Returns this container's effective immediate-element null handling. */ @Internal public final NullHandling onContentNullRead() { diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java index 6f82b2c37e..31cd4238d9 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java @@ -549,9 +549,20 @@ private JsonTypeInfo lenientTypeInfo(JsonTypeInfo typeInfo, int features) { if (codec instanceof ArrayCodec || codec instanceof CollectionCodec) { TypeRef typeRef = typeInfo.typeRef(); Class rawType = typeInfo.rawType(); - TypeRef elementType = - rawType.isArray() ? typeRef.getComponentType() : CodecUtils.elementTypeRef(typeRef); - element = getTypeInfo(elementType); + TypeRef elementType; + if (codec instanceof ArrayCodec) { + elementType = typeRef.getComponentType(); + element = getTypeInfo(elementType); + // A module may own an array carrier with other element semantics, such as unsigned + // arrays. Only the default array representation of the component may be rebuilt. + if (ArrayCodec.create(rawType, element, sharedRegistry.byteArrayFormat()).getClass() + != codec.getClass()) { + return typeInfo; + } + } else { + elementType = CodecUtils.elementTypeRef(typeRef); + element = ((CollectionCodec) codec).elementTypeInfo(); + } LenientReadCodec elementCodec = LenientReadCodec.scalar(element, features); if (elementCodec != null) { // Rebuild only this occurrence with lenient direct elements. The shared element and diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java index 7e651dc8e7..31653ede42 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -44,6 +44,7 @@ import org.apache.fory.json.annotation.JsonProperty; import org.apache.fory.json.annotation.JsonProperty.NullHandling; import org.apache.fory.json.annotation.JsonUnwrapped; +import org.apache.fory.json.codec.ArrayCodec; import org.apache.fory.json.codec.LenientReadCodec; import org.apache.fory.json.resolver.JsonTypeInfo; import org.apache.fory.json.resolver.JsonTypeResolver; @@ -439,6 +440,28 @@ public void elementsAndSingleValues() { } } + public static class UnsignedShorts { + public short[] values; + } + + @Test + public void moduleArrayRepresentationKept() { + ForyJson json = + newJsonBuilder() + .lenientRead(Feature.values()) + .registerCodec( + short[].class, + (type, resolver, runtimeType) -> + ArrayCodec.createUnsignedPrimitive(short[].class, Types.UINT16_ARRAY, false)) + .build(); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + assertEquals( + read(json, "{\"values\":[65535]}", UnsignedShorts.class, representation).values, + new short[] {-1}); + } + assertRejected(json, "{\"values\":5}", UnsignedShorts.class, ""); + } + @Test public void nonNullOccurrence() { ForyJson json = newJson(); From 1e7571437fe8bd6b5e2fae7340e5f2a5da13d5a8 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 16:41:06 +0100 Subject: [PATCH 04/15] fix(java): leave registered JSON container representations strict under leniency Skip lenient element and single-value handling for arrays and collections produced by a registered codec or codec factory; they own their element semantics. Co-Authored-By: Claude Opus 5.5 --- .../apache/fory/json/resolver/JsonTypeResolver.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java index 31cd4238d9..061d07d901 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java @@ -547,18 +547,17 @@ private JsonTypeInfo lenientTypeInfo(JsonTypeInfo typeInfo, int features) { JsonTypeInfo occurrence = typeInfo; JsonTypeInfo element = null; if (codec instanceof ArrayCodec || codec instanceof CollectionCodec) { + // A registered or module factory codec owns its element semantics, such as unsigned arrays + // or custom component codecs; only built-in container representations are rebuilt. + if (typeInfo.factoryKey() != null || typeInfo.exactCodecClass() != null) { + return typeInfo; + } TypeRef typeRef = typeInfo.typeRef(); Class rawType = typeInfo.rawType(); TypeRef elementType; if (codec instanceof ArrayCodec) { elementType = typeRef.getComponentType(); element = getTypeInfo(elementType); - // A module may own an array carrier with other element semantics, such as unsigned - // arrays. Only the default array representation of the component may be rebuilt. - if (ArrayCodec.create(rawType, element, sharedRegistry.byteArrayFormat()).getClass() - != codec.getClass()) { - return typeInfo; - } } else { elementType = CodecUtils.elementTypeRef(typeRef); element = ((CollectionCodec) codec).elementTypeInfo(); From dd9e9035cd27f4f12b2c2099bd36a1b822e18e51 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 16:49:22 +0100 Subject: [PATCH 05/15] fix(java): keep every registered JSON representation strict under leniency Apply the registered-codec exclusion before any lenient dispatch so registered maps and other factory codecs keep their reader, and drop JsonRawValue from the excluded annotations since it only affects writing. Co-Authored-By: Claude Opus 5.5 --- .../fory/json/annotation/JsonLenient.java | 6 +++--- .../fory/json/resolver/JsonTypeResolver.java | 14 ++++++++------ .../org/apache/fory/json/JsonLenientTest.java | 17 +++++++++++++++++ 3 files changed, 28 insertions(+), 9 deletions(-) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java index 38bca21049..6d32c96852 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java @@ -38,9 +38,9 @@ * *

Features apply to the property value and to the direct boolean, numeric, and string elements * of a property-owned array or collection. They apply only where Fory owns the representation: a - * property with {@link JsonCodec}, {@link JsonFormat}, {@link JsonByteArray}, {@link JsonRawValue}, - * {@link JsonUnwrapped}, a registered codec, or a {@link JsonValue} type keeps that representation. - * A class or builder setting applies silently wherever a feature fits the property type; a property + * property with {@link JsonCodec}, {@link JsonFormat}, {@link JsonByteArray}, {@link + * JsonUnwrapped}, a registered codec, or a {@link JsonValue} type keeps that representation. A + * class or builder setting applies silently wherever a feature fits the property type; a property * declaration without any feature that fits its type is rejected when metadata is built. Root * values, map values, and optional contents are not affected. Writing is unaffected. */ diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java index 061d07d901..91e78aab47 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java @@ -539,19 +539,21 @@ public JsonTypeInfo withLenientRead( } private JsonTypeInfo lenientTypeInfo(JsonTypeInfo typeInfo, int features) { + JsonValueCodec codec = typeInfo.valueCodec(); + // A registered or module factory codec owns its representation, including element semantics + // such as unsigned arrays. Object codecs are never registered directly and always use the + // Fory object model, so they remain eligible. + if ((typeInfo.factoryKey() != null || typeInfo.exactCodecClass() != null) + && !(codec instanceof ObjectCodec)) { + return typeInfo; + } LenientReadCodec scalar = LenientReadCodec.scalar(typeInfo, features); if (scalar != null) { return newTypeInfo(typeInfo.typeRef(), JsonFieldKind.OBJECT, scalar, true); } - JsonValueCodec codec = typeInfo.valueCodec(); JsonTypeInfo occurrence = typeInfo; JsonTypeInfo element = null; if (codec instanceof ArrayCodec || codec instanceof CollectionCodec) { - // A registered or module factory codec owns its element semantics, such as unsigned arrays - // or custom component codecs; only built-in container representations are rebuilt. - if (typeInfo.factoryKey() != null || typeInfo.exactCodecClass() != null) { - return typeInfo; - } TypeRef typeRef = typeInfo.typeRef(); Class rawType = typeInfo.rawType(); TypeRef elementType; diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java index 31653ede42..92017fe90e 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -46,6 +46,7 @@ import org.apache.fory.json.annotation.JsonUnwrapped; import org.apache.fory.json.codec.ArrayCodec; import org.apache.fory.json.codec.LenientReadCodec; +import org.apache.fory.json.codec.MapCodec; import org.apache.fory.json.resolver.JsonTypeInfo; import org.apache.fory.json.resolver.JsonTypeResolver; import org.apache.fory.meta.TypeExtMeta; @@ -462,6 +463,22 @@ public void moduleArrayRepresentationKept() { assertRejected(json, "{\"values\":5}", UnsignedShorts.class, ""); } + public static class RegisteredMap { + public Map ext; + } + + @Test + public void registeredMapRepresentationKept() { + ForyJson json = + newJsonBuilder() + .lenientRead(Feature.values()) + .registerCodec( + Map.class, + (type, resolver, runtimeType) -> MapCodec.create(Map.class, type, resolver)) + .build(); + assertRejected(json, "{\"ext\":\"\"}", RegisteredMap.class, ""); + } + @Test public void nonNullOccurrence() { ForyJson json = newJson(); From c10cd6e52dab6bff0d3a08714f00b2a6f9b75261 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 17:01:25 +0100 Subject: [PATCH 06/15] docs(java): clarify JsonLenient placement and empty-string rules; extend lenient tests Document getter placement, which declarations are rejected, and that explicit-null handling does not apply to empty strings; cover boolean text, separate generated codecs per instance, creator codegen, and content null handling. Co-Authored-By: Claude Opus 5.5 --- docs/json/annotations.md | 22 ++++---- .../fory/json/annotation/JsonLenient.java | 22 ++++---- .../org/apache/fory/json/JsonLenientTest.java | 54 +++++++++++++++++++ 3 files changed, 79 insertions(+), 19 deletions(-) diff --git a/docs/json/annotations.md b/docs/json/annotations.md index cc0bc23cdb..a3b54f8bb6 100644 --- a/docs/json/annotations.md +++ b/docs/json/annotations.md @@ -379,13 +379,13 @@ an enum is unaffected. Writing is unaffected. `JsonLenient` accepts common off-spec value shapes when reading a property. Each feature is independent; the annotation without arguments enables all of them: -| Feature | Accepts | Target | -| ----------------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------- | -| `SINGLE_VALUE_AS_ARRAY` | a value other than an array or `null` as a one-element array, for example `"IAB1"` | arrays (except binary-encoded `byte[]`) and collections | -| `SCALAR_AS_STRING` | a number or boolean as its exact token text, for example `1.50` as `"1.50"` | `String` | -| `FLOAT_AS_INT` | a number with a fraction or exponent, truncated toward zero: `300.7` as `300`, `1e3` | `byte`, `short`, `int`, `long`, their boxed types, and `BigInteger` | -| `TRIM_QUOTED_SCALAR` | a quoted boolean or number with surrounding spaces, for example `" 300 "` | boolean and numeric types | -| `EMPTY_STRING_AS_NULL` | `""` as `null`; primitives receive `false` or zero | boolean, numeric, object, map, array, and collection types | +| Feature | Accepts | Target | +| ----------------------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- | +| `SINGLE_VALUE_AS_ARRAY` | a value other than an array or `null` as a one-element array, for example `"IAB1"` | arrays (except binary-encoded `byte[]`) and collections | +| `SCALAR_AS_STRING` | a number or boolean as its exact token text, for example `1.50` as `"1.50"` | `String` | +| `FLOAT_AS_INT` | a number with a fraction or exponent, truncated toward zero: `300.7` as `300`, `1e3` | `byte`, `short`, `int`, `long`, their boxed types, and `BigInteger` | +| `TRIM_QUOTED_SCALAR` | a quoted boolean or number with surrounding spaces, for example `" 300 "` | boolean and numeric types | +| `EMPTY_STRING_AS_NULL` | `""` as `null`; primitives receive `false` or zero | boolean, numeric, object, map, array (except binary `byte[]`), and collection types | ```java import org.apache.fory.json.annotation.JsonLenient; @@ -408,7 +408,7 @@ public final class Imp { With this model, `{"id":123,"cat":"IAB1","w":"300.0"}` reads `id` as `"123"`, `cat` as `[IAB1]`, and `w` as `300`, while `strictCat` still requires a JSON array. -A declaration on a field, setter, or `JsonCreator` parameter replaces the class and builder settings +A declaration on a field, getter, setter, or `JsonCreator` parameter replaces the class and builder settings for that logical property, and `@JsonLenient({})` makes one property strict. A class declaration is the default for every property of that class and replaces the builder's `lenientRead` setting. It is not inherited by subclasses and does not apply to nested objects, which follow their own class @@ -427,8 +427,10 @@ Additional rules: - Truncation still fails for values outside the target range. `TRIM_QUOTED_SCALAR` accepts only spaces around exactly one token: escape sequences and other characters still fail. -- An empty string read into an array or collection is `null`, not a one-element array. -- An empty string is a decoded value, not an explicit JSON null, so `JsonProperty.onNullRead` does +- With `EMPTY_STRING_AS_NULL`, an empty string read into an array or collection is `null`, not a + one-element array. +- An empty string is a decoded value, not an explicit JSON null, so `JsonProperty.onNullRead` and + `onContentNullRead` do not apply to it. - Root values, map values, and optional contents are not affected. Writing is unaffected. diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java index 6d32c96852..2b176c019e 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java @@ -29,8 +29,8 @@ * Accepts common off-spec JSON value shapes when reading a property, as Jackson does by default or * behind its well-known coercion switches. * - *

On a field, setter, or {@link JsonCreator} parameter, the listed features replace the class - * and builder settings for that logical property; {@code @JsonLenient({})} makes one property + *

On a field, getter, setter, or {@link JsonCreator} parameter, the listed features replace the + * class and builder settings for that logical property; {@code @JsonLenient({})} makes one property * strict. On a class, they are the default for every property of that class and replace {@code * ForyJsonBuilder.lenientRead}. A class annotation is not inherited by subclasses and does not * apply to nested objects, which follow their own class setting. An exact-target {@link JsonMixin} @@ -38,11 +38,13 @@ * *

Features apply to the property value and to the direct boolean, numeric, and string elements * of a property-owned array or collection. They apply only where Fory owns the representation: a - * property with {@link JsonCodec}, {@link JsonFormat}, {@link JsonByteArray}, {@link - * JsonUnwrapped}, a registered codec, or a {@link JsonValue} type keeps that representation. A - * class or builder setting applies silently wherever a feature fits the property type; a property - * declaration without any feature that fits its type is rejected when metadata is built. Root - * values, map values, and optional contents are not affected. Writing is unaffected. + * property with {@link JsonCodec}, {@link JsonFormat}, or {@link JsonByteArray}, and a type with a + * registered codec or {@link JsonValue}, keep that representation. A class or builder setting + * applies silently wherever a feature fits the property type and skips other properties. A + * declaration on the property itself is rejected when metadata is built if no feature fits its + * type, or if the property is never read, selects its own representation, is a JSON Any member, or + * is {@link JsonUnwrapped}. Root values, map values, and optional contents are not affected. + * Writing is unaffected. */ @Documented @Retention(RetentionPolicy.RUNTIME) @@ -87,8 +89,10 @@ enum Feature { * An empty JSON string read into a boolean, numeric, object, map, array, or collection target * is read as {@code null}; primitive targets receive {@code false} or zero. With {@link * #TRIM_QUOTED_SCALAR}, a space-only string read into a boolean or numeric target is also - * empty. The value is assigned like any other decoded value: explicit-null handling does not - * apply. Text targets such as strings, enums, and date/time values are not affected. + * empty. The value is assigned like any other decoded value: explicit-null handling ({@link + * JsonProperty#onNullRead()} and {@link JsonProperty#onContentNullRead()}) does not apply, + * while a non-null occurrence still rejects it. Text targets such as strings, enums, date/time + * values, and byte arrays encoded as binary strings are not affected. */ EMPTY_STRING_AS_NULL } diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java index 92017fe90e..7e77d417bb 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -168,6 +168,15 @@ public static class LenientAny { @JsonLenient @JsonAnyProperty public Map values; } + @JsonLenient + public static class ContentNulls { + @JsonProperty(onContentNullRead = NullHandling.FAIL) + public List failing; + + @JsonProperty(onContentNullRead = NullHandling.SKIP) + public Integer[] skipping; + } + @JsonLenient({}) public static class StrictImp { public int w; @@ -509,6 +518,51 @@ public void nonNullOccurrence() { } } + @Test + public void textOfBooleans() { + ForyJson json = newJson(); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + LenientImp imp = + read(json, "{\"id\":true,\"cat\":[false,0]}", LenientImp.class, representation); + assertEquals(imp.id, "true"); + assertEquals(imp.cat, Arrays.asList("false", "0")); + } + } + + @Test + public void strictAndLenientInstancesKeepSeparateCodecs() { + ForyJson strict = newJson(); + ForyJson lenient = newJsonBuilder().lenientRead(Feature.FLOAT_AS_INT).build(); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + assertEquals(read(lenient, "{\"w\":2.5}", Imp.class, representation).w, 2); + assertEquals(read(strict, "{\"w\":2}", Imp.class, representation).w, 2); + } + assertRejected(strict, "{\"w\":2.5}", Imp.class, ""); + assertGeneratedWhenSupported(strict, Imp.class); + assertGeneratedWhenSupported(lenient, Imp.class); + assertGeneratedWhenSupported(lenient, CreatorImp.class); + assertGeneratedWhenSupported(newJson(), LenientCreator.class); + } + + @Test + public void contentNullHandlingAppliesToNullTokens() { + ForyJson json = newJson(); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + ContentNulls nulls = + read( + json, + "{\"failing\":[\" \",1],\"skipping\":[null,\"\",\" 2 \"]}", + ContentNulls.class, + representation); + assertEquals(nulls.failing, Arrays.asList(null, 1)); + assertEquals(nulls.skipping, new Integer[] {null, 2}); + assertEquals( + read(json, "{\"skipping\":\" 3 \"}", ContentNulls.class, representation).skipping, + new Integer[] {3}); + } + assertRejected(json, "{\"failing\":[null]}", ContentNulls.class, ""); + } + @Test public void emptyStringIsNotExplicitNull() { ForyJson json = newJsonBuilder().onNullRead(NullHandling.SKIP).build(); From 3692c5b46cd9bdc28f6dd49381b43a7caab16588 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 17:16:14 +0100 Subject: [PATCH 07/15] fix(java): report lenient truncation overflow by target with position Range-check truncated integers in JsonReader with the target's overflow message and token position, read zero with an out-of-range exponent as zero, and document that padded non-finite literals stay strict. Co-Authored-By: Claude Opus 5.5 --- docs/json/annotations.md | 6 ++-- .../fory/json/annotation/JsonLenient.java | 3 +- .../fory/json/codec/LenientReadCodec.java | 20 ++++--------- .../apache/fory/json/reader/JsonReader.java | 30 +++++++++++++++---- .../org/apache/fory/json/JsonLenientTest.java | 4 ++- 5 files changed, 39 insertions(+), 24 deletions(-) diff --git a/docs/json/annotations.md b/docs/json/annotations.md index a3b54f8bb6..da6a5b2dfa 100644 --- a/docs/json/annotations.md +++ b/docs/json/annotations.md @@ -426,12 +426,12 @@ metadata is built. Additional rules: - Truncation still fails for values outside the target range. `TRIM_QUOTED_SCALAR` accepts only - spaces around exactly one token: escape sequences and other characters still fail. + spaces around exactly one finite token: escape sequences, other characters, and padded + non-finite literals such as `" NaN "` still fail. - With `EMPTY_STRING_AS_NULL`, an empty string read into an array or collection is `null`, not a one-element array. - An empty string is a decoded value, not an explicit JSON null, so `JsonProperty.onNullRead` and - `onContentNullRead` do - not apply to it. + `onContentNullRead` do not apply to it. - Root values, map values, and optional contents are not affected. Writing is unaffected. ## `JsonPropertyOrder` diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java index 2b176c019e..55a6c4c00f 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java @@ -82,7 +82,8 @@ enum Feature { /** * A quoted boolean or number read into a boolean or numeric target may have leading and * trailing spaces inside the quotes, for example {@code " 300 "}. Escapes and other characters - * around the value are not accepted. + * around the value are not accepted, and non-finite floating-point literals such as {@code + * "NaN"} keep their exact quoted form. */ TRIM_QUOTED_SCALAR, /** diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java index dc2341a1f4..6972d2acd1 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java @@ -278,25 +278,17 @@ private Object readTruncated(JsonReader reader) { if (integral == BIG_INTEGER_TARGET) { return reader.readTruncatedBigInteger(); } - long value = reader.readTruncatedLong(); switch (integral) { case INT_TARGET: - if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { - throw new ForyJsonException("Integer overflow"); - } - return (int) value; + return (int) + reader.readTruncatedLong(Integer.MIN_VALUE, Integer.MAX_VALUE, "Integer overflow"); case SHORT_TARGET: - if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) { - throw new ForyJsonException("Short overflow"); - } - return (short) value; + return (short) + reader.readTruncatedLong(Short.MIN_VALUE, Short.MAX_VALUE, "Short overflow"); case BYTE_TARGET: - if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) { - throw new ForyJsonException("Byte overflow"); - } - return (byte) value; + return (byte) reader.readTruncatedLong(Byte.MIN_VALUE, Byte.MAX_VALUE, "Byte overflow"); default: - return value; + return reader.readTruncatedLong(Long.MIN_VALUE, Long.MAX_VALUE, "Long overflow"); } } diff --git a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java index 522a3688fb..c0676f3b0d 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java @@ -1278,11 +1278,11 @@ public final void finishPaddedQuotedScalar() { /** * Reads a native or quoted JSON number as a {@code long}, truncating a fraction or exponent - * toward zero. An integral token uses the strict integer parser; values outside the {@code long} - * range fail. + * toward zero. An integral token uses the strict integer parser; values outside {@code [min, + * max]} fail with the given overflow message at the token position. */ @Internal - public final long readTruncatedLong() { + public final long readTruncatedLong(long min, long max, String overflow) { skipWhitespace(); boolean quoted = position < length() && charAt(position) == '"'; if (quoted) { @@ -1294,12 +1294,15 @@ public final long readTruncatedLong() { position = start; value = readLongToken(); } else { - BigDecimal decimal = truncatedDecimal(start, LONG_MAX_DIGITS, "Long overflow"); + BigDecimal decimal = truncatedDecimal(start, LONG_MAX_DIGITS, overflow); if (decimal.compareTo(LONG_MIN_DECIMAL) < 0 || decimal.compareTo(LONG_MAX_DECIMAL) > 0) { - throw errorAt("Long overflow", start); + throw errorAt(overflow, start); } value = decimal.longValue(); } + if (value < min || value > max) { + throw errorAt(overflow, start); + } if (quoted) { finishQuotedScalar(); } @@ -1343,6 +1346,9 @@ private BigDecimal truncatedDecimal(int start, int maxIntegerDigits, String over try { decimal = new BigDecimal(slice(start, position)); } catch (NumberFormatException e) { + if (zeroMantissa(start)) { + return BigDecimal.ZERO; + } throw errorAt("Number exponent is out of range", start); } if (decimal.signum() == 0 || decimal.abs().compareTo(BigDecimal.ONE) < 0) { @@ -1354,6 +1360,20 @@ private BigDecimal truncatedDecimal(int start, int maxIntegerDigits, String over return decimal.setScale(0, RoundingMode.DOWN); } + // Tests the scanned number token ending at the current position for an all-zero mantissa. + private boolean zeroMantissa(int start) { + for (int i = start; i < position; i++) { + char ch = charAt(i); + if (ch == 'e' || ch == 'E') { + return true; + } + if (ch >= '1' && ch <= '9') { + return false; + } + } + return true; + } + // String content may contain raw spaces but no raw control characters, so lenient padding inside // quotes is limited to spaces. private int scanSpaces(int cursor) { diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java index 7e77d417bb..f003c93290 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -323,6 +323,8 @@ public void nativeShapesUnchanged() { public void truncationLimits() { ForyJson json = newJson(); assertRejected(json, "{\"w\":3e10}", LenientImp.class, "Integer overflow"); + assertRejected(json, "{\"w\":1e20}", LenientImp.class, "Integer overflow at JSON position"); + assertRejected(json, "{\"d\":\" NaN \"}", LenientImp.class, ""); assertRejected(json, "{\"b\":128.5}", LenientImp.class, "Byte overflow"); assertRejected(json, "{\"l\":1e999999999}", LenientImp.class, "Long overflow"); assertRejected(json, "{\"big\":1e20000}", LenientImp.class, "Integer part is too long"); @@ -331,7 +333,7 @@ public void truncationLimits() { LenientImp imp = read( json, - "{\"l\":1e-999999999,\"big\":-0.5,\"w\":-0.0}", + "{\"l\":1e-999999999,\"big\":-0.5,\"w\":-0.0,\"s\":0e-9999999999}", LenientImp.class, representation); assertEquals(imp.l, 0L); From 36749abad3407da27afe804dd87dea80bba2d0c2 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 17:25:27 +0100 Subject: [PATCH 08/15] fix(java): merge @JsonLenient from creator and setter parameters Property-list creators, static factories, and setter parameters now merge a parameter-level @JsonLenient like other property annotations. Co-Authored-By: Claude Opus 5.5 --- .../fory/json/codec/ObjectCodecBuilder.java | 3 + .../org/apache/fory/json/JsonLenientTest.java | 56 +++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java index 930c95c82a..44c331a148 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/ObjectCodecBuilder.java @@ -1692,6 +1692,7 @@ private static JsonCreatorInfo buildCreatorInfo( bindCreatorType(ownerType, creator, i, parameterTypes[i], builder); builder.mergeFormat(parameters[i]); builder.mergeCodec(parameters[i]); + builder.mergeLenient(parameters[i]); builder.mergeUnwrapped(parameters[i]); if (builder.isAny() && !builder.anyReadEnabled()) { throw new ForyJsonException( @@ -3265,6 +3266,7 @@ private void setReadSetter(Class type, Method setter) { mergeIgnore(parameter); mergeFormat(parameter); mergeCodec(parameter); + mergeLenient(parameter); mergeUnwrapped(parameter); if (ignoreRead || field != null && !fieldReadAllowed) { return; @@ -3671,6 +3673,7 @@ private void mergeCreatorParameter(Class type, Parameter parameter) { mergeIgnore(parameter); mergeFormat(parameter); mergeCodec(parameter); + mergeLenient(parameter); mergeUnwrapped(parameter); JsonProperty property = annotations.get(parameter, JsonProperty.class); if (unwrappedAnnotation == null) { diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java index f003c93290..54c3e0d41c 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -152,6 +152,45 @@ public LenientCreator(@JsonProperty("w") int w) { } } + public static final class ListCreator { + public final int w; + public final int h; + + @JsonCreator({"w", "h"}) + public ListCreator(@JsonLenient(Feature.FLOAT_AS_INT) int w, int h) { + this.w = w; + this.h = h; + } + } + + @JsonLenient + public static final class FactoryCreator { + public final int w; + public final int h; + + private FactoryCreator(int w, int h) { + this.w = w; + this.h = h; + } + + @JsonCreator({"w", "h"}) + public static FactoryCreator of(int w, @JsonLenient({}) int h) { + return new FactoryCreator(w, h); + } + } + + public static class SetterParameter { + private int w; + + public int getW() { + return w; + } + + public void setW(@JsonLenient(Feature.FLOAT_AS_INT) int w) { + this.w = w; + } + } + public static class WriteOnly { @JsonLenient public int getW() { @@ -379,6 +418,23 @@ public void propertyAndClassSettings() { assertGeneratedWhenSupported(json, PropertyOnly.class); } + @Test + public void parameterDeclarations() { + ForyJson json = newJson(); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + ListCreator list = read(json, "{\"w\":2.5,\"h\":3}", ListCreator.class, representation); + assertEquals(list.w, 2); + assertEquals(list.h, 3); + FactoryCreator factory = + read(json, "{\"w\":4.5,\"h\":5}", FactoryCreator.class, representation); + assertEquals(factory.w, 4); + assertEquals(factory.h, 5); + assertEquals(read(json, "{\"w\":6.5}", SetterParameter.class, representation).getW(), 6); + } + assertRejected(json, "{\"w\":1,\"h\":2.5}", ListCreator.class, ""); + assertRejected(json, "{\"w\":1,\"h\":2.5}", FactoryCreator.class, ""); + } + @Test public void builderDefault() { ForyJson json = newJsonBuilder().lenientRead(Feature.FLOAT_AS_INT).build(); From 0b4bbf615c3c83c6a28019512e6a0522b9c516e1 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 17:41:51 +0100 Subject: [PATCH 09/15] fix(java): bound lenient BigInteger truncation by token length Limit the integral digits a truncated BigInteger may expand to by its token length (at least the long range), truncate tiny numbers with out-of-range exponents to zero, treat space-only strings as empty for trimmed numeric containers, and test element leniency through generated readers. Co-Authored-By: Claude Opus 5.5 --- docs/json/annotations.md | 10 ++++---- .../fory/json/annotation/JsonLenient.java | 3 ++- .../fory/json/codec/LenientReadCodec.java | 11 ++++++++- .../apache/fory/json/reader/JsonReader.java | 20 +++++++++++++--- .../org/apache/fory/json/JsonLenientTest.java | 24 ++++++++++++++++++- 5 files changed, 58 insertions(+), 10 deletions(-) diff --git a/docs/json/annotations.md b/docs/json/annotations.md index da6a5b2dfa..24edfc80fe 100644 --- a/docs/json/annotations.md +++ b/docs/json/annotations.md @@ -425,11 +425,13 @@ metadata is built. Additional rules: -- Truncation still fails for values outside the target range. `TRIM_QUOTED_SCALAR` accepts only - spaces around exactly one finite token: escape sequences, other characters, and padded - non-finite literals such as `" NaN "` still fail. +- Truncation still fails for values outside the target range. A truncated `BigInteger` may have at + most as many integer digits as its token has characters, and at least 19, so `1e9999` fails. +- `TRIM_QUOTED_SCALAR` accepts only spaces around exactly one finite token: escape sequences, other + characters, and padded non-finite literals such as `" NaN "` still fail. - With `EMPTY_STRING_AS_NULL`, an empty string read into an array or collection is `null`, not a - one-element array. + one-element array. With `TRIM_QUOTED_SCALAR` too, so is a space-only string read into an array or + collection of boolean or numeric elements. - An empty string is a decoded value, not an explicit JSON null, so `JsonProperty.onNullRead` and `onContentNullRead` do not apply to it. - Root values, map values, and optional contents are not affected. Writing is unaffected. diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java index 55a6c4c00f..96f0c2f800 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java @@ -76,7 +76,8 @@ enum Feature { * A JSON number with a fraction or exponent read into a {@code byte}, {@code short}, {@code * int}, {@code long}, their boxed types, or {@code BigInteger} is truncated toward zero, for * example {@code 300.7} as {@code 300} and {@code 1e3} as {@code 1000}. Values outside the - * target range still fail. Quoted numbers are truncated the same way. + * target range still fail, and a {@code BigInteger} may have at most as many integer digits as + * its token has characters, and at least 19. Quoted numbers are truncated the same way. */ FLOAT_AS_INT, /** diff --git a/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java index 6972d2acd1..2ef6955284 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java @@ -163,6 +163,13 @@ public static LenientReadCodec container(JsonTypeInfo base, JsonTypeInfo element if (containerFeatures == 0) { return null; } + // A space-only string is empty for a container of trimmed boolean or numeric elements, as it + // is for those elements themselves, rather than a single blank element. + if (element != null + && element.valueCodec() instanceof ScalarCodec + && ((ScalarCodec) element.valueCodec()).trim) { + containerFeatures |= TRIM_QUOTED_SCALAR; + } if ((containerFeatures & SINGLE_VALUE_AS_ARRAY) == 0) { element = null; } @@ -347,11 +354,13 @@ private static class ContainerCodec extends LenientReadCodec { final JsonTypeInfo element; private final boolean emptyAsNull; + private final boolean blank; private ContainerCodec(JsonTypeInfo base, JsonTypeInfo element, int features) { super(base); this.element = element; emptyAsNull = (features & EMPTY_STRING_AS_NULL) != 0; + blank = (features & TRIM_QUOTED_SCALAR) != 0; } final int shape(JsonReader reader) { @@ -359,7 +368,7 @@ final int shape(JsonReader reader) { if (token == '[' || token == 'n') { return NATIVE; } - if (emptyAsNull && token == '"' && reader.tryReadEmptyString(false)) { + if (emptyAsNull && token == '"' && reader.tryReadEmptyString(blank)) { return EMPTY; } return element == null ? NATIVE : SINGLE; diff --git a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java index c0676f3b0d..42e52e7649 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java @@ -1326,8 +1326,10 @@ public final BigInteger readTruncatedBigInteger() { position = start; value = readBigIntegerToken(); } else { - value = - truncatedDecimal(start, MAX_BIG_NUMBER_LENGTH, "Integer part is too long").toBigInteger(); + // An exponent must not expand a short token into a much longer integer: bound the integral + // digits by the token length, with the long range as the minimum allowance. + int maxDigits = Math.min(MAX_BIG_NUMBER_LENGTH, Math.max(position - start, LONG_MAX_DIGITS)); + value = truncatedDecimal(start, maxDigits, "Integer part is too long").toBigInteger(); } if (quoted) { finishQuotedScalar(); @@ -1346,7 +1348,9 @@ private BigDecimal truncatedDecimal(int start, int maxIntegerDigits, String over try { decimal = new BigDecimal(slice(start, position)); } catch (NumberFormatException e) { - if (zeroMantissa(start)) { + // The exponent is outside the int range; a zero mantissa or a negative exponent still + // truncates to zero because the token holds at most MAX_BIG_NUMBER_LENGTH digits. + if (zeroMantissa(start) || negativeExponent(start)) { return BigDecimal.ZERO; } throw errorAt("Number exponent is out of range", start); @@ -1374,6 +1378,16 @@ private boolean zeroMantissa(int start) { return true; } + private boolean negativeExponent(int start) { + for (int i = start; i < position; i++) { + char ch = charAt(i); + if (ch == 'e' || ch == 'E') { + return i + 1 < position && charAt(i + 1) == '-'; + } + } + return false; + } + // String content may contain raw spaces but no raw control characters, so lenient padding inside // quotes is limited to spaces. private int scanSpaces(int cursor) { diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java index 54c3e0d41c..31911f12de 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -339,6 +339,15 @@ public void emptyStrings() { assertEquals(imp.d, 0d); assertEquals(imp.nums, Arrays.asList(null, 1)); assertNull(imp.sizes); + imp = + read( + json, + "{\"sizes\":\" \",\"nums\":\" \",\"cat\":\" \"}", + LenientImp.class, + representation); + assertNull(imp.sizes); + assertNull(imp.nums); + assertEquals(imp.cat, Collections.singletonList(" ")); } } @@ -367,16 +376,19 @@ public void truncationLimits() { assertRejected(json, "{\"b\":128.5}", LenientImp.class, "Byte overflow"); assertRejected(json, "{\"l\":1e999999999}", LenientImp.class, "Long overflow"); assertRejected(json, "{\"big\":1e20000}", LenientImp.class, "Integer part is too long"); + assertRejected(json, "{\"big\":1e9999}", LenientImp.class, "Integer part is too long"); assertRejected(json, "{\"l\":1e9999999999}", LenientImp.class, "exponent is out of range"); for (int representation = 0; representation < REPRESENTATIONS; representation++) { LenientImp imp = read( json, - "{\"l\":1e-999999999,\"big\":-0.5,\"w\":-0.0,\"s\":0e-9999999999}", + "{\"l\":1e-9999999999,\"big\":-0.5,\"w\":-0.0,\"s\":0e-9999999999," + + "\"boxedLong\":1e18}", LenientImp.class, representation); assertEquals(imp.l, 0L); assertEquals(imp.big, BigInteger.ZERO); + assertEquals(imp.boxedLong, Long.valueOf(1_000_000_000_000_000_000L)); assertEquals(imp.w, 0); } } @@ -598,6 +610,16 @@ public void strictAndLenientInstancesKeepSeparateCodecs() { assertRejected(strict, "{\"w\":2.5}", Imp.class, ""); assertGeneratedWhenSupported(strict, Imp.class); assertGeneratedWhenSupported(lenient, Imp.class); + ForyJson text = newJsonBuilder().lenientRead(Feature.SCALAR_AS_STRING).build(); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + Imp imp = read(lenient, "{\"nums\":[1.5],\"sizes\":[2.7]}", Imp.class, representation); + assertEquals(imp.nums, Collections.singletonList(1)); + assertEquals(imp.sizes, new int[] {2}); + assertEquals( + read(text, "{\"cat\":[1,true]}", Imp.class, representation).cat, + Arrays.asList("1", "true")); + } + assertGeneratedWhenSupported(text, Imp.class); assertGeneratedWhenSupported(lenient, CreatorImp.class); assertGeneratedWhenSupported(newJson(), LenientCreator.class); } From 951531f09cf3e02099f5f5bb41502039978f16ad Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 17:56:41 +0100 Subject: [PATCH 10/15] fix(java): report out-of-range whole numbers by lenient target type Route integral tokens that may not fit a long through the decimal range check so FLOAT_AS_INT reports the target's overflow message, and document that EMPTY_STRING_AS_NULL skips JsonSubTypes bases and dynamic Object targets. Co-Authored-By: Claude Opus 5.5 --- docs/json/annotations.md | 15 ++++++++------- .../apache/fory/json/annotation/JsonLenient.java | 15 ++++++++------- .../org/apache/fory/json/reader/JsonReader.java | 5 ++++- .../org/apache/fory/json/JsonLenientTest.java | 8 ++++++++ 4 files changed, 28 insertions(+), 15 deletions(-) diff --git a/docs/json/annotations.md b/docs/json/annotations.md index 24edfc80fe..20cbb92391 100644 --- a/docs/json/annotations.md +++ b/docs/json/annotations.md @@ -379,13 +379,13 @@ an enum is unaffected. Writing is unaffected. `JsonLenient` accepts common off-spec value shapes when reading a property. Each feature is independent; the annotation without arguments enables all of them: -| Feature | Accepts | Target | -| ----------------------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- | -| `SINGLE_VALUE_AS_ARRAY` | a value other than an array or `null` as a one-element array, for example `"IAB1"` | arrays (except binary-encoded `byte[]`) and collections | -| `SCALAR_AS_STRING` | a number or boolean as its exact token text, for example `1.50` as `"1.50"` | `String` | -| `FLOAT_AS_INT` | a number with a fraction or exponent, truncated toward zero: `300.7` as `300`, `1e3` | `byte`, `short`, `int`, `long`, their boxed types, and `BigInteger` | -| `TRIM_QUOTED_SCALAR` | a quoted boolean or number with surrounding spaces, for example `" 300 "` | boolean and numeric types | -| `EMPTY_STRING_AS_NULL` | `""` as `null`; primitives receive `false` or zero | boolean, numeric, object, map, array (except binary `byte[]`), and collection types | +| Feature | Accepts | Target | +| ----------------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- | +| `SINGLE_VALUE_AS_ARRAY` | a value other than an array or `null` as a one-element array, for example `"IAB1"` | arrays (except binary-encoded `byte[]`) and collections | +| `SCALAR_AS_STRING` | a number or boolean as its exact token text, for example `1.50` as `"1.50"` | `String` | +| `FLOAT_AS_INT` | a number with a fraction or exponent, truncated toward zero: `300.7` as `300`, `1e3` | `byte`, `short`, `int`, `long`, their boxed types, and `BigInteger` | +| `TRIM_QUOTED_SCALAR` | a quoted boolean or number with surrounding spaces, for example `" 300 "` | boolean and numeric types | +| `EMPTY_STRING_AS_NULL` | `""` as `null`; primitives receive `false` or zero | boolean, numeric, non-polymorphic object, map, array (except binary `byte[]`), and collection types | ```java import org.apache.fory.json.annotation.JsonLenient; @@ -434,6 +434,7 @@ Additional rules: collection of boolean or numeric elements. - An empty string is a decoded value, not an explicit JSON null, so `JsonProperty.onNullRead` and `onContentNullRead` do not apply to it. +- `EMPTY_STRING_AS_NULL` does not apply to `JsonSubTypes` bases or dynamic `Object` targets. - Root values, map values, and optional contents are not affected. Writing is unaffected. ## `JsonPropertyOrder` diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java index 96f0c2f800..0950d62b6a 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java @@ -88,13 +88,14 @@ enum Feature { */ TRIM_QUOTED_SCALAR, /** - * An empty JSON string read into a boolean, numeric, object, map, array, or collection target - * is read as {@code null}; primitive targets receive {@code false} or zero. With {@link - * #TRIM_QUOTED_SCALAR}, a space-only string read into a boolean or numeric target is also - * empty. The value is assigned like any other decoded value: explicit-null handling ({@link - * JsonProperty#onNullRead()} and {@link JsonProperty#onContentNullRead()}) does not apply, - * while a non-null occurrence still rejects it. Text targets such as strings, enums, date/time - * values, and byte arrays encoded as binary strings are not affected. + * An empty JSON string read into a boolean, numeric, non-polymorphic object, map, array, or + * collection target is read as {@code null}; primitive targets receive {@code false} or zero. + * With {@link #TRIM_QUOTED_SCALAR}, a space-only string read into a boolean or numeric target + * is also empty. The value is assigned like any other decoded value: explicit-null handling + * ({@link JsonProperty#onNullRead()} and {@link JsonProperty#onContentNullRead()}) does not + * apply, while a non-null occurrence still rejects it. Text targets such as strings, enums, + * date/time values, byte arrays encoded as binary strings, {@link JsonSubTypes} bases, and + * dynamic {@code Object} targets are not affected. */ EMPTY_STRING_AS_NULL } diff --git a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java index 42e52e7649..ae06b0957b 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java @@ -113,6 +113,7 @@ public abstract class JsonReader { private static final BigDecimal LONG_MIN_DECIMAL = BigDecimal.valueOf(Long.MIN_VALUE); private static final BigDecimal LONG_MAX_DECIMAL = BigDecimal.valueOf(Long.MAX_VALUE); private static final int LONG_MAX_DIGITS = 19; + private static final int LONG_SAFE_TOKEN_LENGTH = 18; private static final int DOUBLE_FAST_MAX_SCALE = 15; private static final long DOUBLE_FAST_MAX_UNSCALED = 1L << 53; private static final int DOUBLE_FRACTION_BITS = 52; @@ -1290,7 +1291,9 @@ public final long readTruncatedLong(long min, long max, String overflow) { } int start = position; long value; - if (scanNumberToken() == -1L) { + // An integral token of at most 18 characters always fits a long. Longer tokens use the decimal + // range check so overflow reports the target's message, as for fractional tokens. + if (scanNumberToken() == -1L && position - start <= LONG_SAFE_TOKEN_LENGTH) { position = start; value = readLongToken(); } else { diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java index 31911f12de..87f47149fc 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -372,6 +372,14 @@ public void truncationLimits() { ForyJson json = newJson(); assertRejected(json, "{\"w\":3e10}", LenientImp.class, "Integer overflow"); assertRejected(json, "{\"w\":1e20}", LenientImp.class, "Integer overflow at JSON position"); + assertRejected(json, "{\"w\":99999999999999999999}", LenientImp.class, "Integer overflow"); + assertRejected(json, "{\"w\":\"-99999999999999999999\"}", LenientImp.class, "Integer overflow"); + assertRejected(json, "{\"l\":9223372036854775808}", LenientImp.class, "Long overflow"); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + assertEquals( + read(json, "{\"l\":-9223372036854775808}", LenientImp.class, representation).l, + Long.MIN_VALUE); + } assertRejected(json, "{\"d\":\" NaN \"}", LenientImp.class, ""); assertRejected(json, "{\"b\":128.5}", LenientImp.class, "Byte overflow"); assertRejected(json, "{\"l\":1e999999999}", LenientImp.class, "Long overflow"); From 119c6f85c6950aa049d88cf61d24e508f4e0b936 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 18:01:28 +0100 Subject: [PATCH 11/15] fix(java): keep lenient whole-number reads on the integer parser Do not re-parse whole numbers beyond the long range only to report a target-specific overflow message; the integer parser's own error is sufficient. Co-Authored-By: Claude Opus 5.5 --- .../main/java/org/apache/fory/json/reader/JsonReader.java | 7 +++---- .../test/java/org/apache/fory/json/JsonLenientTest.java | 3 +-- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java index ae06b0957b..0d99e67a03 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java @@ -113,7 +113,6 @@ public abstract class JsonReader { private static final BigDecimal LONG_MIN_DECIMAL = BigDecimal.valueOf(Long.MIN_VALUE); private static final BigDecimal LONG_MAX_DECIMAL = BigDecimal.valueOf(Long.MAX_VALUE); private static final int LONG_MAX_DIGITS = 19; - private static final int LONG_SAFE_TOKEN_LENGTH = 18; private static final int DOUBLE_FAST_MAX_SCALE = 15; private static final long DOUBLE_FAST_MAX_UNSCALED = 1L << 53; private static final int DOUBLE_FRACTION_BITS = 52; @@ -1291,9 +1290,9 @@ public final long readTruncatedLong(long min, long max, String overflow) { } int start = position; long value; - // An integral token of at most 18 characters always fits a long. Longer tokens use the decimal - // range check so overflow reports the target's message, as for fractional tokens. - if (scanNumberToken() == -1L && position - start <= LONG_SAFE_TOKEN_LENGTH) { + // Integral tokens keep the allocation-free integer parser; its own long overflow error is + // sufficient, so a whole number beyond the long range is not re-parsed for a target message. + if (scanNumberToken() == -1L) { position = start; value = readLongToken(); } else { diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java index 87f47149fc..45ba84c3bc 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -372,8 +372,7 @@ public void truncationLimits() { ForyJson json = newJson(); assertRejected(json, "{\"w\":3e10}", LenientImp.class, "Integer overflow"); assertRejected(json, "{\"w\":1e20}", LenientImp.class, "Integer overflow at JSON position"); - assertRejected(json, "{\"w\":99999999999999999999}", LenientImp.class, "Integer overflow"); - assertRejected(json, "{\"w\":\"-99999999999999999999\"}", LenientImp.class, "Integer overflow"); + assertRejected(json, "{\"w\":99999999999999999999}", LenientImp.class, "overflow"); assertRejected(json, "{\"l\":9223372036854775808}", LenientImp.class, "Long overflow"); for (int representation = 0; representation < REPRESENTATIONS; representation++) { assertEquals( From 2b2e617f3ba55ca2d1cec450da81f627b3d60970 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 18:17:24 +0100 Subject: [PATCH 12/15] fix(java): truncate fraction-only lenient numbers from their integer part Without an exponent, parse only the integer part of a lenient truncated number after checking its digit count, document that conflicting member declarations are rejected, and test unaffected targets and one-sided padding. Co-Authored-By: Claude Opus 5.5 --- docs/json/annotations.md | 2 +- .../fory/json/annotation/JsonLenient.java | 4 +- .../apache/fory/json/reader/JsonReader.java | 24 ++++++++--- .../org/apache/fory/json/JsonLenientTest.java | 42 +++++++++++++++++++ 4 files changed, 64 insertions(+), 8 deletions(-) diff --git a/docs/json/annotations.md b/docs/json/annotations.md index 20cbb92391..325d0bf45a 100644 --- a/docs/json/annotations.md +++ b/docs/json/annotations.md @@ -421,7 +421,7 @@ is `[1, 2, null]`. They apply only where Fory owns the representation: propertie A class or builder setting applies silently wherever a feature fits the property type. A property declaration with no feature that fits the property type, or one on a property that is never read, selects its own representation, is an Any member, or is unwrapped, is rejected when the class -metadata is built. +metadata is built. So are different feature sets declared on members of the same property. Additional rules: diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java index 0950d62b6a..7997b264e4 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java @@ -43,8 +43,8 @@ * applies silently wherever a feature fits the property type and skips other properties. A * declaration on the property itself is rejected when metadata is built if no feature fits its * type, or if the property is never read, selects its own representation, is a JSON Any member, or - * is {@link JsonUnwrapped}. Root values, map values, and optional contents are not affected. - * Writing is unaffected. + * is {@link JsonUnwrapped}, and so are different feature sets declared on members of one property. + * Root values, map values, and optional contents are not affected. Writing is unaffected. */ @Documented @Retention(RetentionPolicy.RUNTIME) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java index 0d99e67a03..8d65da920d 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java @@ -1292,11 +1292,12 @@ public final long readTruncatedLong(long min, long max, String overflow) { long value; // Integral tokens keep the allocation-free integer parser; its own long overflow error is // sufficient, so a whole number beyond the long range is not re-parsed for a target message. - if (scanNumberToken() == -1L) { + long separators = scanNumberToken(); + if (separators == -1L) { position = start; value = readLongToken(); } else { - BigDecimal decimal = truncatedDecimal(start, LONG_MAX_DIGITS, overflow); + BigDecimal decimal = truncatedDecimal(start, separators, LONG_MAX_DIGITS, overflow); if (decimal.compareTo(LONG_MIN_DECIMAL) < 0 || decimal.compareTo(LONG_MAX_DECIMAL) > 0) { throw errorAt(overflow, start); } @@ -1324,14 +1325,16 @@ public final BigInteger readTruncatedBigInteger() { } int start = position; BigInteger value; - if (scanNumberToken() == -1L) { + long separators = scanNumberToken(); + if (separators == -1L) { position = start; value = readBigIntegerToken(); } else { // An exponent must not expand a short token into a much longer integer: bound the integral // digits by the token length, with the long range as the minimum allowance. int maxDigits = Math.min(MAX_BIG_NUMBER_LENGTH, Math.max(position - start, LONG_MAX_DIGITS)); - value = truncatedDecimal(start, maxDigits, "Integer part is too long").toBigInteger(); + value = + truncatedDecimal(start, separators, maxDigits, "Integer part is too long").toBigInteger(); } if (quoted) { finishQuotedScalar(); @@ -1342,10 +1345,21 @@ public final BigInteger readTruncatedBigInteger() { // Parses the scanned token ending at the current position and drops its fraction. Magnitudes // below one return zero before scaling, and the integral digit count is bounded before any // exponent is expanded, so a huge exponent cannot drive allocation or work. - private BigDecimal truncatedDecimal(int start, int maxIntegerDigits, String overflow) { + private BigDecimal truncatedDecimal( + int start, long separators, int maxIntegerDigits, String overflow) { if (position - start > MAX_BIG_NUMBER_LENGTH) { throw errorAt("Number is too long", start); } + int point = (int) (separators >> 32); + if ((int) separators < 0) { + // Without an exponent the truncated value is the integer part, so the fraction digits are + // never parsed and the integral digit count is checked before any allocation. + int digits = point - start - (charAt(start) == '-' ? 1 : 0); + if (digits > maxIntegerDigits) { + throw errorAt(overflow, start); + } + return new BigDecimal(slice(start, point)); + } BigDecimal decimal; try { decimal = new BigDecimal(slice(start, position)); diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java index 45ba84c3bc..758e7db92a 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -33,6 +33,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.apache.fory.json.annotation.JsonAnyProperty; import org.apache.fory.json.annotation.JsonByteArray; @@ -43,6 +44,7 @@ import org.apache.fory.json.annotation.JsonMixin; import org.apache.fory.json.annotation.JsonProperty; import org.apache.fory.json.annotation.JsonProperty.NullHandling; +import org.apache.fory.json.annotation.JsonSubTypes; import org.apache.fory.json.annotation.JsonUnwrapped; import org.apache.fory.json.codec.ArrayCodec; import org.apache.fory.json.codec.LenientReadCodec; @@ -216,6 +218,22 @@ public static class ContentNulls { public Integer[] skipping; } + @JsonSubTypes( + property = "kind", + value = @JsonSubTypes.Type(value = Circle.class, name = "circle")) + public interface Shape {} + + public static class Circle implements Shape { + public int r; + } + + @JsonLenient + public static class Unaffected { + public Shape shape; + public Object any; + public Optional optional; + } + @JsonLenient({}) public static class StrictImp { public int w; @@ -492,6 +510,30 @@ public void invalidDeclarations() { assertRejected(json, "{\"id\":1}", LenientAny.class, "JSON Any"); } + @Test + public void unaffectedTargets() { + ForyJson json = newJson(); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + Unaffected unaffected = read(json, "{\"any\":\"\"}", Unaffected.class, representation); + assertEquals(unaffected.any, ""); + } + assertRejected(json, "{\"shape\":\"\"}", Unaffected.class, ""); + assertRejected(json, "{\"optional\":\" 5 \"}", Unaffected.class, ""); + assertRejected(json, "{\"d\":\" -Infinity \"}", LenientImp.class, ""); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + LenientImp imp = + read( + json, + "{\"w\":\" 2\",\"h\":\"3 \",\"l\":12.99,\"big\":-0.99}", + LenientImp.class, + representation); + assertEquals(imp.w, 2); + assertEquals(imp.h, Integer.valueOf(3)); + assertEquals(imp.l, 12L); + assertEquals(imp.big, BigInteger.ZERO); + } + } + @Test public void controlCharactersAreNotPadding() { ForyJson json = newJson(); From 33c532ecd1a83218bf34a139797cde69aa790a47 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 18:30:47 +0100 Subject: [PATCH 13/15] test(java): cover lenient declaration reach; clarify unboxed rejection Report unboxed value properties separately when @JsonLenient is declared on them, document that other methods are ignored, and test non-inheritance, nested objects, getter declarations, and JsonValue types. Co-Authored-By: Claude Opus 5.5 --- docs/json/annotations.md | 3 +- .../fory/json/annotation/JsonLenient.java | 3 +- .../fory/json/resolver/JsonTypeResolver.java | 11 ++-- .../org/apache/fory/json/JsonLenientTest.java | 56 +++++++++++++++++++ 4 files changed, 67 insertions(+), 6 deletions(-) diff --git a/docs/json/annotations.md b/docs/json/annotations.md index 325d0bf45a..81b47ca32a 100644 --- a/docs/json/annotations.md +++ b/docs/json/annotations.md @@ -409,7 +409,8 @@ With this model, `{"id":123,"cat":"IAB1","w":"300.0"}` reads `id` as `"123"`, `c `w` as `300`, while `strictCat` still requires a JSON array. A declaration on a field, getter, setter, or `JsonCreator` parameter replaces the class and builder settings -for that logical property, and `@JsonLenient({})` makes one property strict. A class declaration is +for that logical property, and `@JsonLenient({})` makes one property strict. On any other method, +including a `JsonCreator` method itself, the annotation is not used. A class declaration is the default for every property of that class and replaces the builder's `lenientRead` setting. It is not inherited by subclasses and does not apply to nested objects, which follow their own class setting. An exact-target Mixin can supply or replace either declaration. diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java index 7997b264e4..fbffc14fd7 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java @@ -31,7 +31,8 @@ * *

On a field, getter, setter, or {@link JsonCreator} parameter, the listed features replace the * class and builder settings for that logical property; {@code @JsonLenient({})} makes one property - * strict. On a class, they are the default for every property of that class and replace {@code + * strict; on any other method, including a {@link JsonCreator} method itself, the annotation is not + * used. On a class, they are the default for every property of that class and replace {@code * ForyJsonBuilder.lenientRead}. A class annotation is not inherited by subclasses and does not * apply to nested objects, which follow their own class setting. An exact-target {@link JsonMixin} * may supply or replace either declaration. diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java index 91e78aab47..0fe9ac29aa 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonTypeResolver.java @@ -508,9 +508,10 @@ public JsonTypeInfo withContentNullRead(JsonTypeInfo typeInfo, NullHandling hand /** * Resolves the read occurrence of a property with lenient features. Features apply only to - * Fory-owned representations; {@code typeInfo} is {@code null} and {@code selected} is true when - * the property selects its own representation. The occurrence is returned unchanged when no - * feature fits, which is rejected for a feature set declared on the property itself. + * Fory-owned representations; {@code typeInfo} is {@code null} for an unboxed value property, and + * {@code selected} is true when the property selects its own representation. The occurrence is + * returned unchanged when no feature fits, which is rejected for a feature set declared on the + * property itself. */ @Internal public JsonTypeInfo withLenientRead( @@ -523,7 +524,9 @@ public JsonTypeInfo withLenientRead( if (typeInfo == null || selected) { if (declared) { throw new ForyJsonException( - "@JsonLenient requires the default representation of JSON property " + property); + typeInfo == null + ? "@JsonLenient is not supported on unboxed value property " + property + : "@JsonLenient requires the default representation of JSON property " + property); } return typeInfo; } diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java index 758e7db92a..323d1ca971 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -46,6 +46,7 @@ import org.apache.fory.json.annotation.JsonProperty.NullHandling; import org.apache.fory.json.annotation.JsonSubTypes; import org.apache.fory.json.annotation.JsonUnwrapped; +import org.apache.fory.json.annotation.JsonValue; import org.apache.fory.json.codec.ArrayCodec; import org.apache.fory.json.codec.LenientReadCodec; import org.apache.fory.json.codec.MapCodec; @@ -234,6 +235,46 @@ public static class Unaffected { public Optional optional; } + public static class InheritsNothing extends Defaults { + public int w; + } + + @JsonLenient + public static class NestedOwner { + public Banner banner; + } + + public static class GetterDeclared { + private int w; + + @JsonLenient(Feature.FLOAT_AS_INT) + public int getW() { + return w; + } + + public void setW(int w) { + this.w = w; + } + } + + public static final class Wrapped { + private final int value; + + @JsonCreator + public Wrapped(int value) { + this.value = value; + } + + @JsonValue + public int value() { + return value; + } + } + + public static class ValueOwner { + public Wrapped wrapped; + } + @JsonLenient({}) public static class StrictImp { public int w; @@ -534,6 +575,21 @@ public void unaffectedTargets() { } } + @Test + public void declarationReach() { + ForyJson json = newJson(); + ForyJson all = newJsonBuilder().lenientRead(Feature.values()).build(); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + assertEquals(read(json, "{\"w\":2.5}", GetterDeclared.class, representation).getW(), 2); + assertEquals( + read(json, "{\"banner\":{\"w\":3}}", NestedOwner.class, representation).banner.w, 3); + } + assertRejected(json, "{\"h\":\" 1 \"}", InheritsNothing.class, ""); + assertRejected(json, "{\"banner\":{\"w\":2.5}}", NestedOwner.class, ""); + assertRejected(all, "{\"wrapped\":2.5}", ValueOwner.class, ""); + assertRejected(all, "{\"wrapped\":\"\"}", ValueOwner.class, ""); + } + @Test public void controlCharactersAreNotPadding() { ForyJson json = newJson(); From e12ea5095c1a73d9f978a0b5aa6875302392333e Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 18:45:44 +0100 Subject: [PATCH 14/15] perf(java): truncate lenient numbers from digit positions without whole-token parsing Decide the truncated integer's digit count from the mantissa digits and the clamped exponent before any allocation, and build only the surviving digits, so long mantissas with exponents no longer parse the whole token. Co-Authored-By: Claude Opus 5.5 --- .../apache/fory/json/reader/JsonReader.java | 96 ++++++++++--------- .../org/apache/fory/json/JsonLenientTest.java | 24 ++++- 2 files changed, 74 insertions(+), 46 deletions(-) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java index 8d65da920d..71c340c4b9 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/reader/JsonReader.java @@ -23,7 +23,6 @@ import java.lang.invoke.MethodType; import java.math.BigDecimal; import java.math.BigInteger; -import java.math.RoundingMode; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; @@ -113,6 +112,7 @@ public abstract class JsonReader { private static final BigDecimal LONG_MIN_DECIMAL = BigDecimal.valueOf(Long.MIN_VALUE); private static final BigDecimal LONG_MAX_DECIMAL = BigDecimal.valueOf(Long.MAX_VALUE); private static final int LONG_MAX_DIGITS = 19; + private static final long TRUNCATION_EXPONENT_LIMIT = 2L * MAX_BIG_NUMBER_LENGTH; private static final int DOUBLE_FAST_MAX_SCALE = 15; private static final long DOUBLE_FAST_MAX_UNSCALED = 1L << 53; private static final int DOUBLE_FRACTION_BITS = 52; @@ -1342,66 +1342,72 @@ public final BigInteger readTruncatedBigInteger() { return value; } - // Parses the scanned token ending at the current position and drops its fraction. Magnitudes - // below one return zero before scaling, and the integral digit count is bounded before any - // exponent is expanded, so a huge exponent cannot drive allocation or work. + // Truncates the scanned token ending at the current position toward zero without parsing it as a + // whole. The token's mantissa holds at most MAX_BIG_NUMBER_LENGTH digits, so the result's + // integral + // digit count is decided from the digit positions and the clamped exponent before any + // allocation, and only the digits that survive truncation are materialized. private BigDecimal truncatedDecimal( int start, long separators, int maxIntegerDigits, String overflow) { if (position - start > MAX_BIG_NUMBER_LENGTH) { throw errorAt("Number is too long", start); } int point = (int) (separators >> 32); - if ((int) separators < 0) { - // Without an exponent the truncated value is the integer part, so the fraction digits are - // never parsed and the integral digit count is checked before any allocation. - int digits = point - start - (charAt(start) == '-' ? 1 : 0); - if (digits > maxIntegerDigits) { - throw errorAt(overflow, start); - } - return new BigDecimal(slice(start, point)); - } - BigDecimal decimal; - try { - decimal = new BigDecimal(slice(start, position)); - } catch (NumberFormatException e) { - // The exponent is outside the int range; a zero mantissa or a negative exponent still - // truncates to zero because the token holds at most MAX_BIG_NUMBER_LENGTH digits. - if (zeroMantissa(start) || negativeExponent(start)) { - return BigDecimal.ZERO; - } - throw errorAt("Number exponent is out of range", start); + int exponentOffset = (int) separators; + boolean negative = charAt(start) == '-'; + int integerStart = negative ? start + 1 : start; + int mantissaEnd = exponentOffset >= 0 ? exponentOffset : position; + int integerLength = (point >= 0 ? point : mantissaEnd) - integerStart; + int fractionStart = point >= 0 ? point + 1 : mantissaEnd; + int mantissaLength = integerLength + mantissaEnd - fractionStart; + int leadingZeros = 0; + while (leadingZeros < mantissaLength + && mantissaDigit(leadingZeros, integerStart, integerLength, fractionStart) == '0') { + leadingZeros++; + } + if (leadingZeros == mantissaLength) { + return BigDecimal.ZERO; } - if (decimal.signum() == 0 || decimal.abs().compareTo(BigDecimal.ONE) < 0) { + long exponent = exponentOffset >= 0 ? truncationExponent(exponentOffset + 1) : 0; + long resultDigits = integerLength + exponent - leadingZeros; + if (resultDigits <= 0) { return BigDecimal.ZERO; } - if ((long) decimal.precision() - decimal.scale() > maxIntegerDigits) { + if (resultDigits > maxIntegerDigits) { throw errorAt(overflow, start); } - return decimal.setScale(0, RoundingMode.DOWN); + StringBuilder digits = new StringBuilder((int) resultDigits + 1); + if (negative) { + digits.append('-'); + } + long end = leadingZeros + resultDigits; + for (int i = leadingZeros; i < end; i++) { + digits.append( + i < mantissaLength ? mantissaDigit(i, integerStart, integerLength, fractionStart) : '0'); + } + return new BigDecimal(digits.toString()); } - // Tests the scanned number token ending at the current position for an all-zero mantissa. - private boolean zeroMantissa(int start) { - for (int i = start; i < position; i++) { - char ch = charAt(i); - if (ch == 'e' || ch == 'E') { - return true; - } - if (ch >= '1' && ch <= '9') { - return false; - } - } - return true; + private char mantissaDigit(int index, int integerStart, int integerLength, int fractionStart) { + return index < integerLength + ? charAt(integerStart + index) + : charAt(fractionStart + index - integerLength); } - private boolean negativeExponent(int start) { - for (int i = start; i < position; i++) { - char ch = charAt(i); - if (ch == 'e' || ch == 'E') { - return i + 1 < position && charAt(i + 1) == '-'; - } + // Reads the already validated exponent digits. Magnitudes past twice the mantissa digit limit + // cannot change the outcome, so the value is clamped instead of overflowing. + private long truncationExponent(int offset) { + boolean negative = false; + char sign = charAt(offset); + if (sign == '-' || sign == '+') { + negative = sign == '-'; + offset++; } - return false; + long value = 0; + for (int i = offset; i < position && value <= TRUNCATION_EXPONENT_LIMIT; i++) { + value = value * 10 + charAt(i) - '0'; + } + return negative ? -value : value; } // String content may contain raw spaces but no raw control characters, so lenient padding inside diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java index 323d1ca971..5cc5cab788 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -443,7 +443,29 @@ public void truncationLimits() { assertRejected(json, "{\"l\":1e999999999}", LenientImp.class, "Long overflow"); assertRejected(json, "{\"big\":1e20000}", LenientImp.class, "Integer part is too long"); assertRejected(json, "{\"big\":1e9999}", LenientImp.class, "Integer part is too long"); - assertRejected(json, "{\"l\":1e9999999999}", LenientImp.class, "exponent is out of range"); + assertRejected(json, "{\"l\":1e9999999999}", LenientImp.class, "Long overflow"); + String longFraction = "1." + repeat('9', 9990); + assertRejected(json, "{\"w\":" + longFraction + "e10}", LenientImp.class, "Integer overflow"); + for (int representation = 0; representation < REPRESENTATIONS; representation++) { + LenientImp imp = + read( + json, + "{\"w\":" + + longFraction + + "e0,\"big\":" + + longFraction + + "e2,\"l\":-1.99e1," + + "\"h\":\"0.00123e4\",\"s\":123e-2,\"b\":5e-1,\"boxedLong\":12.5e1}", + LenientImp.class, + representation); + assertEquals(imp.w, 1); + assertEquals(imp.big, BigInteger.valueOf(199)); + assertEquals(imp.l, -19L); + assertEquals(imp.h, Integer.valueOf(12)); + assertEquals(imp.s, (short) 1); + assertEquals(imp.b, (byte) 0); + assertEquals(imp.boxedLong, Long.valueOf(125)); + } for (int representation = 0; representation < REPRESENTATIONS; representation++) { LenientImp imp = read( From 8fb6c242a22cb76b7c84b61f562e603e73d3d621 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 17 Nov 2026 20:04:54 +0100 Subject: [PATCH 15/15] fix(java): initialize JsonLenient features at native-image build time JsonConfig retains the builder's lenient feature set, so the enum must be build-time initialized like the other configuration enums. Co-Authored-By: Claude Opus 5.5 --- .../org.apache.fory/fory-json/native-image.properties | 1 + .../org/apache/fory/json/ForyJsonGraalVMFeatureJarVerifier.java | 1 + 2 files changed, 2 insertions(+) diff --git a/java/fory-json/src/main/resources/META-INF/native-image/org.apache.fory/fory-json/native-image.properties b/java/fory-json/src/main/resources/META-INF/native-image/org.apache.fory/fory-json/native-image.properties index 7e729bc50b..b058690bd9 100644 --- a/java/fory-json/src/main/resources/META-INF/native-image/org.apache.fory/fory-json/native-image.properties +++ b/java/fory-json/src/main/resources/META-INF/native-image/org.apache.fory/fory-json/native-image.properties @@ -30,6 +30,7 @@ Args=--features=org.apache.fory.json.ForyJsonGraalVMFeature \ org.apache.fory.json.JsonTypeCheckContext,\ org.apache.fory.json.PropertyNamingStrategy,\ org.apache.fory.json.annotation.JsonByteArray$Format,\ + org.apache.fory.json.annotation.JsonLenient$Feature,\ org.apache.fory.json.annotation.JsonProperty$Include,\ org.apache.fory.json.annotation.JsonProperty$NullHandling,\ org.apache.fory.util.function.ObjBooleanConsumer,\ diff --git a/java/fory-json/src/test/java/org/apache/fory/json/ForyJsonGraalVMFeatureJarVerifier.java b/java/fory-json/src/test/java/org/apache/fory/json/ForyJsonGraalVMFeatureJarVerifier.java index de258897f7..8db55ad38d 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/ForyJsonGraalVMFeatureJarVerifier.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/ForyJsonGraalVMFeatureJarVerifier.java @@ -64,6 +64,7 @@ public final class ForyJsonGraalVMFeatureJarVerifier { + "org.apache.fory.json.JsonTypeCheckContext," + "org.apache.fory.json.PropertyNamingStrategy," + "org.apache.fory.json.annotation.JsonByteArray$Format," + + "org.apache.fory.json.annotation.JsonLenient$Feature," + "org.apache.fory.json.annotation.JsonProperty$Include," + "org.apache.fory.json.annotation.JsonProperty$NullHandling," + "org.apache.fory.util.function.ObjBooleanConsumer,"