diff --git a/docs/json/annotations.md b/docs/json/annotations.md index 69deba4065..81b47ca32a 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,70 @@ 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 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; +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, getter, setter, or `JsonCreator` parameter replaces the class and builder settings +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. + +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 is never read, +selects its own representation, is an Any member, or is unwrapped, is rejected when the class +metadata is built. So are different feature sets declared on members of the same property. + +Additional rules: + +- 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. 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. +- `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` `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..fbffc14fd7 --- /dev/null +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonLenient.java @@ -0,0 +1,103 @@ +/* + * 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, 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 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. + * + *

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}, 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}, 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) +@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, 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, + /** + * 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, and non-finite floating-point literals such as {@code + * "NaN"} keep their exact quoted form. + */ + TRIM_QUOTED_SCALAR, + /** + * 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/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..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 @@ -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 @@ -307,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/codec/LenientReadCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java new file mode 100644 index 0000000000..2ef6955284 --- /dev/null +++ b/java/fory-json/src/main/java/org/apache/fory/json/codec/LenientReadCodec.java @@ -0,0 +1,436 @@ +/* + * 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; + } + // 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; + } + return array + ? new ArrayElementCodec(base, element, containerFeatures, base.rawType().getComponentType()) + : 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); + } + + @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(); + } + switch (integral) { + case INT_TARGET: + return (int) + reader.readTruncatedLong(Integer.MIN_VALUE, Integer.MAX_VALUE, "Integer overflow"); + case SHORT_TARGET: + return (short) + reader.readTruncatedLong(Short.MIN_VALUE, Short.MAX_VALUE, "Short overflow"); + case BYTE_TARGET: + return (byte) reader.readTruncatedLong(Byte.MIN_VALUE, Byte.MAX_VALUE, "Byte overflow"); + default: + return reader.readTruncatedLong(Long.MIN_VALUE, Long.MAX_VALUE, "Long overflow"); + } + } + + 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 ? emptyReference() : 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 ? emptyReference() : 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 ? emptyReference() : 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 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) { + char token = reader.peekToken(); + if (token == '[' || token == 'n') { + return NATIVE; + } + if (emptyAsNull && token == '"' && reader.tryReadEmptyString(blank)) { + 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 emptyReference(); + 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 emptyReference(); + 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 emptyReference(); + 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) { + 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 baebb5cdc1..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 @@ -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); @@ -1683,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( @@ -1706,7 +1716,8 @@ private static JsonCreatorInfo buildCreatorInfo( builder.formatAnnotation(), builder.creatorUnboxedRequired, builder.onNullRead(), - builder.explicitContentNullRead)); + builder.explicitContentNullRead, + builder.lenientRead())); } } } else { @@ -1783,6 +1794,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 +1832,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 +1976,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 +3126,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 +3145,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 +3186,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; @@ -3237,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; @@ -3312,6 +3342,7 @@ private boolean hasConfiguration() { || rawValueSource != null || valueCodecClass != null || formatAnnotation != null + || lenientAnnotation != null || unwrappedAnnotation != null; } @@ -3328,6 +3359,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; } @@ -3378,6 +3413,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); @@ -3429,7 +3468,8 @@ private JsonFieldInfo build( rawValue, escapeNonAscii, onNullRead(), - explicitContentNullRead); + explicitContentNullRead, + lenientRead()); } private void validateUnwrapped(Class type, JsonCreatorInfo creatorInfo) { @@ -3437,6 +3477,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 +3567,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"); @@ -3628,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) { @@ -3682,6 +3728,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..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 @@ -109,6 +109,10 @@ 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 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; @@ -1199,6 +1203,227 @@ 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 spaces + * 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 = scanSpaces(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 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 + */ + @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 = scanSpaces(contentStart); + if (tokenStart == close + || tokenStart == contentStart && charAt(close - 1) != ' ' + || isJsonWhitespace(charAt(tokenStart))) { + return false; + } + position = tokenStart; + return true; + } + + /** Consumes trailing spaces and the closing quote after {@link #beginPaddedQuotedScalar()}. */ + @Internal + public final void finishPaddedQuotedScalar() { + position = scanSpaces(position); + 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 {@code [min, + * max]} fail with the given overflow message at the token position. + */ + @Internal + public final long readTruncatedLong(long min, long max, String overflow) { + skipWhitespace(); + boolean quoted = position < length() && charAt(position) == '"'; + if (quoted) { + beginQuotedScalar(); + } + int start = position; + 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. + long separators = scanNumberToken(); + if (separators == -1L) { + position = start; + value = readLongToken(); + } else { + 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); + } + value = decimal.longValue(); + } + if (value < min || value > max) { + throw errorAt(overflow, start); + } + 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; + 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, separators, maxDigits, "Integer part is too long").toBigInteger(); + } + if (quoted) { + finishQuotedScalar(); + } + return value; + } + + // 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); + 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; + } + long exponent = exponentOffset >= 0 ? truncationExponent(exponentOffset + 1) : 0; + long resultDigits = integerLength + exponent - leadingZeros; + if (resultDigits <= 0) { + return BigDecimal.ZERO; + } + if (resultDigits > maxIntegerDigits) { + throw errorAt(overflow, start); + } + 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()); + } + + private char mantissaDigit(int index, int integerStart, int integerLength, int fractionStart) { + return index < integerLength + ? charAt(integerStart + index) + : charAt(fractionStart + index - integerLength); + } + + // 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++; + } + 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 + // 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'; + } + 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..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 @@ -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,92 @@ 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} 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( + 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( + typeInfo == null + ? "@JsonLenient is not supported on unboxed value property " + property + : "@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) { + 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); + } + JsonTypeInfo occurrence = typeInfo; + JsonTypeInfo element = null; + if (codec instanceof ArrayCodec || codec instanceof CollectionCodec) { + TypeRef typeRef = typeInfo.typeRef(); + Class rawType = typeInfo.rawType(); + TypeRef elementType; + if (codec instanceof ArrayCodec) { + elementType = typeRef.getComponentType(); + element = getTypeInfo(elementType); + } 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 + // 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/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," 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..5cc5cab788 --- /dev/null +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonLenientTest.java @@ -0,0 +1,782 @@ +/* + * 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.Optional; +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; +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.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; +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; + +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; + public byte[] data; + } + + @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 final class LenientCreator { + private final int w; + + @JsonCreator + public LenientCreator(@JsonProperty("w") int w) { + this.w = 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() { + 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 ContentNulls { + @JsonProperty(onContentNullRead = NullHandling.FAIL) + public List failing; + + @JsonProperty(onContentNullRead = NullHandling.SKIP) + 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; + } + + 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; + } + + 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); + imp = + read( + json, + "{\"sizes\":\" \",\"nums\":\" \",\"cat\":\" \"}", + LenientImp.class, + representation); + assertNull(imp.sizes); + assertNull(imp.nums); + assertEquals(imp.cat, Collections.singletonList(" ")); + } + } + + @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, "{\"w\":1e20}", LenientImp.class, "Integer overflow at JSON position"); + assertRejected(json, "{\"w\":99999999999999999999}", LenientImp.class, "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"); + 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, "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( + json, + "{\"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); + } + } + + @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 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(); + 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"); + 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 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 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(); + 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}); + } + } + + 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, ""); + } + + 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(); + 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 + 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); + 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); + } + + @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(); + 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,