Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
a121aac
feat(java): opt-in lenient reading of off-spec JSON value shapes
pavel-ptashyts Nov 17, 2026
18f0ab6
fix(java): keep lenient JSON reads within non-null and string rules
pavel-ptashyts Nov 17, 2026
2dea259
fix(java): keep module-owned JSON array representations strict under …
pavel-ptashyts Nov 17, 2026
1e75714
fix(java): leave registered JSON container representations strict und…
pavel-ptashyts Nov 17, 2026
dd9e903
fix(java): keep every registered JSON representation strict under len…
pavel-ptashyts Nov 17, 2026
c10cd6e
docs(java): clarify JsonLenient placement and empty-string rules; ext…
pavel-ptashyts Nov 17, 2026
3692c5b
fix(java): report lenient truncation overflow by target with position
pavel-ptashyts Nov 17, 2026
36749ab
fix(java): merge @JsonLenient from creator and setter parameters
pavel-ptashyts Nov 17, 2026
0b4bbf6
fix(java): bound lenient BigInteger truncation by token length
pavel-ptashyts Nov 17, 2026
951531f
fix(java): report out-of-range whole numbers by lenient target type
pavel-ptashyts Nov 17, 2026
119c6f8
fix(java): keep lenient whole-number reads on the integer parser
pavel-ptashyts Nov 17, 2026
2b2e617
fix(java): truncate fraction-only lenient numbers from their integer …
pavel-ptashyts Nov 17, 2026
33c532e
test(java): cover lenient declaration reach; clarify unboxed rejection
pavel-ptashyts Nov 17, 2026
e12ea50
perf(java): truncate lenient numbers from digit positions without who…
pavel-ptashyts Nov 17, 2026
8fb6c24
fix(java): initialize JsonLenient features at native-image build time
pavel-ptashyts Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 65 additions & 1 deletion docs/json/annotations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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<String> cat;
public int w;

@JsonLenient({})
public List<String> strictCat;

@JsonLenient(Feature.SINGLE_VALUE_AS_ARRAY)
public List<Banner> 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<Integer>` 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
Expand Down
19 changes: 19 additions & 0 deletions docs/json/object-mapping.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -83,6 +84,7 @@ final class JsonMixinAnnotations {
JSON_FORMAT,
JSON_IGNORE,
JSON_INCLUDE,
JSON_LENIENT,
JSON_PROPERTY,
JSON_PROPERTY_ORDER,
JSON_RAW_VALUE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -59,6 +61,8 @@ public final class ForyJsonBuilder {
private boolean escapeNonAscii;
private boolean failOnMissingRequiredProperties;
private boolean failOnDuplicateProperties;
private final EnumSet<JsonLenient.Feature> lenientRead =
EnumSet.noneOf(JsonLenient.Feature.class);
private JsonByteArray.Format byteArrayFormat = JsonByteArray.Format.BASE64;
private boolean codegenEnabled = true;
private boolean asyncCompilationEnabled = true;
Expand Down Expand Up @@ -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.
*
* <p>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<JsonLenient.Feature> 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}.
Expand Down Expand Up @@ -460,6 +485,7 @@ JsonConfig buildConfig() {
escapeNonAscii,
failOnMissingRequiredProperties,
failOnDuplicateProperties,
lenientRead,
byteArrayFormat,
effectiveCodegen,
effectiveAsyncCompilation,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -46,6 +49,7 @@ public final class JsonConfig {
private final boolean escapeNonAscii;
private final boolean failOnMissingRequiredProperties;
private final boolean failOnDuplicateProperties;
private final Set<JsonLenient.Feature> lenientRead;
private final JsonByteArray.Format byteArrayFormat;
private final boolean codegenEnabled;
private final boolean asyncCompilationEnabled;
Expand All @@ -72,6 +76,7 @@ public final class JsonConfig {
boolean escapeNonAscii,
boolean failOnMissingRequiredProperties,
boolean failOnDuplicateProperties,
Set<JsonLenient.Feature> lenientRead,
JsonByteArray.Format byteArrayFormat,
boolean codegenEnabled,
boolean asyncCompilationEnabled,
Expand All @@ -95,6 +100,9 @@ public final class JsonConfig {
this.escapeNonAscii = escapeNonAscii;
this.failOnMissingRequiredProperties = failOnMissingRequiredProperties;
this.failOnDuplicateProperties = failOnDuplicateProperties;
EnumSet<JsonLenient.Feature> 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;
Expand Down Expand Up @@ -157,6 +165,11 @@ public boolean failOnDuplicateProperties() {
return failOnDuplicateProperties;
}

/** Returns the lenient read features applied to properties without a declared setting. */
public Set<JsonLenient.Feature> lenientRead() {
return lenientRead;
}

/** Returns the default byte-array representation for both reading and writing. */
public JsonByteArray.Format byteArrayFormat() {
return byteArrayFormat;
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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.
*
* <p>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<String>}. 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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ public abstract class ArrayCodec<T> implements ContainerJsonCodec<T> {
@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 <T> JsonValueCodec<T> create(
Class<T> arrayType, TypeRef<?> arrayTypeRef, JsonTypeResolver resolver) {
if (!arrayType.isArray()) {
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading