From 28a9d3ea931d68ccff26fc22cab01d2dc06938ed Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 20:51:06 +0100 Subject: [PATCH 01/26] feat(java): add class-level default codecs to fory-json Co-Authored-By: Claude Opus 5.5 --- docs/json/annotations.md | 2 +- docs/json/custom-codecs.md | 56 ++- .../processing/JsonMixinAnnotations.java | 4 + .../processing/JsonTypeProcessor.java | 49 +++ .../processing/JsonTypeProcessorTest.java | 49 +++ .../json/annotation/JsonDefaultCodec.java | 70 +++ .../fory/json/codec/ObjectCodecBuilder.java | 37 +- .../fory/json/resolver/JsonDefaultCodecs.java | 358 +++++++++++++++ .../json/resolver/JsonMixinAnnotations.java | 3 + .../fory/json/ForyJsonGraalVMFeature.java | 23 + .../fory/json/JsonDefaultCodecTest.java | 415 ++++++++++++++++++ 11 files changed, 1054 insertions(+), 12 deletions(-) create mode 100644 java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java create mode 100644 java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java create mode 100644 java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java diff --git a/docs/json/annotations.md b/docs/json/annotations.md index 69deba4065..993cf38a3d 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`, +`JsonDefaultCodec`, `JsonDuplicateProperties`, `JsonFormat`, `JsonIgnore`, `JsonInclude`, `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. diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index efa517df0f..98cfc2846d 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -266,6 +266,48 @@ The child members have these meanings: | `keyCodec` | `Map` | JSON member name for `K` | | `valueCodec` | `Map` | direct `V` value | +### Class defaults with `JsonDefaultCodec` + +Use `@JsonDefaultCodec` on a class when every property of one type needs the same occurrence codec. +Built-in scalar types such as `BigDecimal` cannot be registered with `registerCodec`, so this is +the way to give them one representation across a model without annotating each property: + +```java +import java.math.BigDecimal; +import java.util.List; +import java.util.Optional; +import org.apache.fory.json.annotation.JsonDefaultCodec; + +@JsonDefaultCodec(PlainDecimalCodec.class) +public class Invoice { + public BigDecimal total; // PlainDecimalCodec + public Optional discount; // contentCodec = PlainDecimalCodec + public List lines; // elementCodec = PlainDecimalCodec + @JsonCodec(OtherDecimalCodec.class) + public BigDecimal tax; // the property declaration wins +} +``` + +Each codec targets the type argument it declares for `JsonValueCodec`. `PlainDecimalCodec extends +AbstractJsonValueCodec` targets `BigDecimal`, and a codec declared over +`Optional` targets exactly that parameterized type. The target must be concrete. List +several codecs in one annotation, `@JsonDefaultCodec({A.class, B.class})`, or repeat the annotation; +one class may name at most one codec per target type. + +A property or creator parameter whose resolved type equals a target uses the codec as if it +declared `@JsonCodec(value = ...)`; a primitive property matches its wrapper type. Otherwise a +target equal to the direct child of an array, `Collection`, `AtomicReferenceArray`, `Optional`, +`AtomicReference`, or the value of a `Map` fills the matching child member from the table above. +Deeper nesting is not searched. A child that a complete codec of its container hides is left +unchanged instead of failing. + +Properties that declare `JsonCodec`, `JsonFormat`, `JsonByteArray`, `JsonRawValue`, or +`JsonUnwrapped`, and JSON Any properties, do not use defaults. Defaults declared on superclasses +apply to the subclass, and a subclass default for the same target type replaces the inherited one. +Defaults stop at the class boundary: a nested object type uses its own declarations. An +exact-target Mixin may supply or replace the annotation; a Mixin that supplies or removes either +the single or the repeated form replaces both forms declared on the target. + ### Kotlin occurrences Kotlin uses the same codec registrations and `JsonCodec` annotation. Apply property annotations to @@ -352,13 +394,13 @@ The first `JsonAnySetter` parameter is the String property name. Its second para Fory resolves each current value in this order: -| Priority | Source | -| -------: | ------------------------------------------------- | -| 1 | Current property or parameter `JsonCodec` | -| 2 | Exact `registerCodec` registration | -| 3 | Exact-target type `JsonCodec` after Mixin overlay | -| 4 | Inherited-frontier type `JsonCodec` declaration | -| 5 | Built-in or default JSON mapping | +| Priority | Source | +| -------: | ------------------------------------------------------------------------ | +| 1 | Current property or parameter `JsonCodec`, else class `JsonDefaultCodec` | +| 2 | Exact `registerCodec` registration | +| 3 | Exact-target type `JsonCodec` after Mixin overlay | +| 4 | Inherited-frontier type `JsonCodec` declaration | +| 5 | Built-in or default JSON mapping | One logical property may expose the annotation from its field, getter, setter parameter, creator parameter, or record propagation. Repeated configurations must be identical; Fory does not merge 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..0187864ef6 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 @@ -56,6 +56,8 @@ final class JsonMixinAnnotations { private static final String JSON_BYTE_ARRAY = JSON_PACKAGE + ".annotation.JsonByteArray"; private static final String JSON_CODEC = JSON_PACKAGE + ".annotation.JsonCodec"; private static final String JSON_CREATOR = JSON_PACKAGE + ".annotation.JsonCreator"; + private static final String JSON_DEFAULT_CODEC = JSON_PACKAGE + ".annotation.JsonDefaultCodec"; + private static final String JSON_DEFAULT_CODEC_LIST = JSON_DEFAULT_CODEC + ".List"; private static final String JSON_DUPLICATE_PROPERTIES = JSON_PACKAGE + ".annotation.JsonDuplicateProperties"; private static final String JSON_FORMAT = JSON_PACKAGE + ".annotation.JsonFormat"; @@ -79,6 +81,8 @@ final class JsonMixinAnnotations { JSON_BYTE_ARRAY, JSON_CODEC, JSON_CREATOR, + JSON_DEFAULT_CODEC, + JSON_DEFAULT_CODEC_LIST, JSON_DUPLICATE_PROPERTIES, JSON_FORMAT, JSON_IGNORE, diff --git a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java index 197916aea9..40f3abe643 100644 --- a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java +++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java @@ -64,6 +64,8 @@ final class JsonTypeProcessor { private static final String JSON_MIXIN = JSON_PACKAGE + ".annotation.JsonMixin"; private static final String JSON_MIXIN_REMOVE = JSON_PACKAGE + ".annotation.JsonMixinRemove"; private static final String JSON_CODEC = JSON_PACKAGE + ".annotation.JsonCodec"; + private static final String JSON_DEFAULT_CODEC = JSON_PACKAGE + ".annotation.JsonDefaultCodec"; + private static final String JSON_DEFAULT_CODEC_LIST = JSON_DEFAULT_CODEC + ".List"; private static final String JSON_SUB_TYPES = JSON_PACKAGE + ".annotation.JsonSubTypes"; private static final String JSON_SUBTYPE_GENERATION = JSON_PACKAGE + ".codec.GeneratedJsonSubtypeTable.Generation"; @@ -476,6 +478,14 @@ private Model inspectModel(TypeElement target, JsonMixinAnnotations annotations) for (TypeElement type : classes) { collectAnnotations(annotations, type, model.annotationTypes); collectCodecAnnotation(annotationMirror(annotations, type, JSON_CODEC), model); + collectDefaultCodecs(annotationMirror(annotations, type, JSON_DEFAULT_CODEC), model); + AnnotationMirror defaultCodecList = + annotationMirror(annotations, type, JSON_DEFAULT_CODEC_LIST); + if (defaultCodecList != null) { + for (AnnotationMirror defaultCodec : annotationMirrors(defaultCodecList)) { + collectDefaultCodecs(defaultCodec, model); + } + } if (hasJsonAnnotations(annotations, type)) { model.annotationOwnerTypes.add(elements.getBinaryName(type).toString()); } @@ -602,6 +612,45 @@ private void collectCodecAnnotation(AnnotationMirror annotation, Model model) { } } + /** Retains the codec classes a class-level {@code JsonDefaultCodec} may select at runtime. */ + private void collectDefaultCodecs(AnnotationMirror annotation, Model model) { + if (annotation == null) { + return; + } + AnnotationValue value = annotationValue(annotation, "value"); + if (value == null || !(value.getValue() instanceof List)) { + return; + } + for (Object entry : (List) value.getValue()) { + Object codecType = + entry instanceof AnnotationValue ? ((AnnotationValue) entry).getValue() : null; + TypeElement codec = + codecType instanceof TypeMirror ? asTypeElement((TypeMirror) codecType) : null; + if (codec != null) { + model.codecTypes.add(elements.getBinaryName(codec).toString()); + } + } + } + + private static List annotationMirrors(AnnotationMirror container) { + List mirrors = new ArrayList<>(); + for (Map.Entry member : + container.getElementValues().entrySet()) { + if (!member.getKey().getSimpleName().contentEquals("value") + || !(member.getValue().getValue() instanceof List)) { + continue; + } + for (Object entry : (List) member.getValue().getValue()) { + Object mirror = + entry instanceof AnnotationValue ? ((AnnotationValue) entry).getValue() : null; + if (mirror instanceof AnnotationMirror) { + mirrors.add((AnnotationMirror) mirror); + } + } + } + return mirrors; + } + private void emitR8(Model model) { String resourceName = (model.mixin == null ? R8_PREFIX : R8_MIXIN_PREFIX) + model.resourceIdentity + ".pro"; diff --git a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java index 73b9c2a09f..fca1d225e3 100644 --- a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java +++ b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java @@ -1617,6 +1617,55 @@ public void codecMemberRules() throws Exception { assertTrue(rules.contains("class java.util.HashMap { public (); }"), rules); } + @Test + public void defaultCodecRules() throws Exception { + String codec = + " public static final class %s extends org.apache.fory.json.codec.AbstractJsonValueCodec<%s> {\n" + + " public void write(org.apache.fory.json.writer.JsonWriter writer, %s value) {}\n" + + " public %s read(org.apache.fory.json.reader.JsonReader reader) { return null; }\n" + + " }\n"; + Map sources = new LinkedHashMap<>(); + sources.put( + "test.DefaultCodecBase", + "package test;\n" + + "import org.apache.fory.json.annotation.JsonDefaultCodec;\n" + + "@JsonDefaultCodec(DefaultCodecBase.BaseCodec.class)\n" + + "public class DefaultCodecBase {\n" + + String.format(codec, "BaseCodec", "Long", "Long", "Long") + + " public Long id;\n" + + "}\n"); + sources.put( + "test.DefaultCodecModel", + "package test;\n" + + "import java.math.BigDecimal;\n" + + "import java.util.Optional;\n" + + "import org.apache.fory.json.annotation.JsonDefaultCodec;\n" + + "import org.apache.fory.json.annotation.JsonType;\n" + + "@JsonType\n" + + "@JsonDefaultCodec(DefaultCodecModel.DecimalCodec.class)\n" + + "@JsonDefaultCodec(DefaultCodecModel.OptionalCodec.class)\n" + + "public class DefaultCodecModel extends DefaultCodecBase {\n" + + String.format(codec, "DecimalCodec", "BigDecimal", "BigDecimal", "BigDecimal") + + String.format( + codec, + "OptionalCodec", + "Optional", + "Optional", + "Optional") + + " public BigDecimal price;\n" + + " public Optional bid = Optional.empty();\n" + + "}\n"); + CompilationResult result = compile(sources); + assertTrue(result.success, result.diagnostics()); + String rules = result.generatedResource(RULE_PREFIX + "test.DefaultCodecModel.pro"); + assertTrue( + rules.contains("class test.DefaultCodecModel$DecimalCodec { public (); }"), rules); + assertTrue( + rules.contains("class test.DefaultCodecModel$OptionalCodec { public (); }"), rules); + assertTrue(rules.contains("class test.DefaultCodecBase$BaseCodec { public (); }"), rules); + assertTrue(rules.contains("org.apache.fory.json.annotation.JsonDefaultCodec"), rules); + } + @Test public void unwrappedMemberRules() throws Exception { CompilationResult result = diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java new file mode 100644 index 0000000000..2702736263 --- /dev/null +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java @@ -0,0 +1,70 @@ +/* + * 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.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import org.apache.fory.json.codec.JsonValueCodec; + +/** + * Selects default codecs for the properties of the annotated class by their declared type. + * + *

Codecs may be listed in one annotation, {@code @JsonDefaultCodec({A.class, B.class})}, or in + * repeated annotations, {@code @JsonDefaultCodec(A.class) @JsonDefaultCodec(B.class)}. + * + *

Each codec targets the type argument it declares for {@link JsonValueCodec}: a codec of {@code + * BigDecimal} targets {@code BigDecimal}, a codec of {@code Optional} targets exactly + * {@code Optional}. That type must be concrete, without type variables or wildcards, + * and one class may name at most one codec per target type. + * + *

A property or creator parameter whose resolved type equals a target uses that codec as if it + * declared {@code @JsonCodec(value = ...)}; a primitive property matches its wrapper type. Without + * a whole-type match, a target that equals the direct child of an array, {@code Collection}, {@code + * AtomicReferenceArray}, {@code Optional}, {@code AtomicReference}, or the value of a {@code Map} + * is used as the matching {@link JsonCodec} child member. A child that a complete codec of its + * container would hide is left unchanged. + * + *

A property that declares its own {@link JsonCodec}, {@link JsonFormat}, {@link JsonByteArray}, + * {@link JsonRawValue}, or {@link JsonUnwrapped}, and JSON Any properties, do not use defaults. + * Defaults declared on superclasses apply too, and a subclass default for the same target type + * replaces the inherited one. Defaults do not reach nested object types, which use their own class + * declarations. An exact-target {@link JsonMixin} may supply or replace this annotation; supplying + * or removing either the single or the repeated form replaces both forms declared on the target. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Repeatable(JsonDefaultCodec.List.class) +public @interface JsonDefaultCodec { + /** Returns the default codecs; each targets its declared value type. */ + Class>[] value(); + + /** Container of repeated {@link JsonDefaultCodec} declarations on one class. */ + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE) + @interface List { + JsonDefaultCodec[] 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..de075d0131 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 @@ -74,6 +74,7 @@ import org.apache.fory.json.meta.JsonFieldInfo; import org.apache.fory.json.meta.JsonFieldNameHash; import org.apache.fory.json.meta.JsonValidatorInfo; +import org.apache.fory.json.resolver.JsonDefaultCodecs; import org.apache.fory.json.resolver.JsonSharedRegistry; import org.apache.fory.platform.GraalvmSupport; import org.apache.fory.reflect.ObjectInstantiator; @@ -1560,7 +1561,7 @@ private static JsonCreatorInfo buildRecordCreatorInfo( i, resolved, rawTypes[i], - builder.codecAnnotation(), + builder.effectiveCodec(resolved), builder.valueCodecClass(), builder.formatAnnotation(), builder.creatorUnboxedRequired, @@ -1693,7 +1694,7 @@ private static JsonCreatorInfo buildCreatorInfo( } if (!builder.isAny() && builder.unwrappedAnnotation == null) { TypeRef resolved = ownerType.resolveType(parameterTypes[i]); - JsonCodec codecAnnotation = builder.codecAnnotation(); + JsonCodec codecAnnotation = builder.effectiveCodec(resolved); Class> valueCodecClass = builder.valueCodecClass(); fields.add( new JsonCreatorFieldInfo( @@ -1775,6 +1776,13 @@ private static JsonCreatorInfo buildCreatorInfo( builder == null ? annotations.get(parameters[i], JsonUnwrapped.class) : builder.unwrappedAnnotation; + if (builder == null) { + if (codecAnnotation == null && formatAnnotation == null && unwrapped == null) { + codecAnnotation = annotations.defaultCodecs.select(resolved); + } + } else { + codecAnnotation = builder.effectiveCodec(resolved); + } if (unwrapped != null) { if (builder == null && (property.onNullRead() != NullHandling.DEFAULT @@ -1955,7 +1963,7 @@ private static JsonCreatorInfo buildObjectModelCreatorInfo( i, resolved, rawTypes[i], - builder.codecAnnotation(), + builder.effectiveCodec(resolved), builder.valueCodecClass(), builder.formatAnnotation(), builder.creatorUnboxedRequired, @@ -3109,10 +3117,12 @@ private static Type boxedType(Type type) { private static final class Annotations { private final Class targetType; private final JsonSharedRegistry registry; + private final JsonDefaultCodecs defaultCodecs; private Annotations(Class targetType, JsonSharedRegistry registry) { this.targetType = targetType; this.registry = registry; + defaultCodecs = JsonDefaultCodecs.of(targetType, registry); } private A get(AnnotatedElement element, Class annotationType) { @@ -3423,7 +3433,9 @@ private JsonFieldInfo build( readAccessor, ownerType, objectModelType, - codecAnnotation, + usesDefaultCodec() + ? annotations.defaultCodecs.select(logicalTypeRef(ownerType)) + : codecAnnotation, valueCodecClass, formatAnnotation, rawValue, @@ -3510,6 +3522,23 @@ private JsonCodec codecAnnotation() { return codecAnnotation; } + /** + * Returns the declared codec, or the class default for {@code type} when nothing is declared. + */ + private JsonCodec effectiveCodec(TypeRef type) { + return usesDefaultCodec() ? annotations.defaultCodecs.select(type) : codecAnnotation; + } + + private boolean usesDefaultCodec() { + return !annotations.defaultCodecs.isEmpty() + && codecAnnotation == null + && valueCodecClass == null + && formatAnnotation == null + && rawValueSource == null + && unwrappedAnnotation == null + && !isAny(); + } + private Class> valueCodecClass() { return valueCodecClass; } diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java new file mode 100644 index 0000000000..6e991cf2f0 --- /dev/null +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -0,0 +1,358 @@ +/* + * 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.resolver; + +import java.lang.annotation.Annotation; +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.atomic.AtomicReferenceArray; +import org.apache.fory.annotation.Internal; +import org.apache.fory.json.ForyJsonException; +import org.apache.fory.json.annotation.JsonCodec; +import org.apache.fory.json.annotation.JsonDefaultCodec; +import org.apache.fory.json.codec.CodecUtils; +import org.apache.fory.json.codec.JsonValueCodec; +import org.apache.fory.json.codec.MapKeyCodec; +import org.apache.fory.reflect.TypeRef; + +/** + * Effective {@link JsonDefaultCodec} declarations of one object type and its superclasses. + * + *

Selection turns a matching default into the {@link JsonCodec} configuration a property would + * declare itself, so codec resolution, validation, and generated code follow the occurrence path. + */ +@Internal +public final class JsonDefaultCodecs { + private static final JsonDefaultCodecs NONE = new JsonDefaultCodecs(null, new Entry[0]); + + private final JsonSharedRegistry registry; + private final Entry[] entries; + + private JsonDefaultCodecs(JsonSharedRegistry registry, Entry[] entries) { + this.registry = registry; + this.entries = entries; + } + + /** Collects the defaults of {@code type}; a subclass entry replaces a superclass one. */ + public static JsonDefaultCodecs of(Class type, JsonSharedRegistry registry) { + List entries = null; + for (Class declaring = type; + declaring != null && declaring != Object.class; + declaring = declaring.getSuperclass()) { + JsonDefaultCodec single = registry.annotation(type, declaring, JsonDefaultCodec.class); + JsonDefaultCodec.List repeated = + registry.annotation(type, declaring, JsonDefaultCodec.List.class); + // Java stores repeated declarations in the container, so a Mixin that supplies or removes + // either form replaces both forms declared on the target. + boolean singleReplaced = + !Objects.equals( + single, JsonMixinAnnotations.targetAnnotation(declaring, JsonDefaultCodec.class)); + boolean repeatedReplaced = + !Objects.equals( + repeated, + JsonMixinAnnotations.targetAnnotation(declaring, JsonDefaultCodec.List.class)); + if (singleReplaced && !repeatedReplaced) { + repeated = null; + } else if (repeatedReplaced && !singleReplaced) { + single = null; + } + List annotations = new ArrayList<>(); + if (single != null) { + annotations.add(single); + } + if (repeated != null) { + annotations.addAll(Arrays.asList(repeated.value())); + } + if (annotations.isEmpty()) { + continue; + } + List declared = new ArrayList<>(); + for (JsonDefaultCodec annotation : annotations) { + for (Class> codecClass : annotation.value()) { + Entry entry = new Entry(targetType(declaring, codecClass), codecClass); + if (find(declared, entry.target) != null) { + throw new ForyJsonException( + "Duplicate @JsonDefaultCodec target " + + entry.target.getTypeName() + + " on " + + declaring.getName()); + } + declared.add(entry); + } + } + if (entries == null) { + entries = declared; + } else { + for (Entry entry : declared) { + if (find(entries, entry.target) == null) { + entries.add(entry); + } + } + } + } + return entries == null ? NONE : new JsonDefaultCodecs(registry, entries.toArray(new Entry[0])); + } + + public boolean isEmpty() { + return entries.length == 0; + } + + /** Returns the codec configuration for a property of {@code type}, or null without a match. */ + public JsonCodec select(TypeRef type) { + if (entries.length == 0) { + return null; + } + TypeRef declared = type.isPrimitive() ? type.wrap() : type; + Class> codec = codec(declared.getType()); + if (codec != null) { + return new SelectedCodec(codec, null, null, null); + } + Class rawType = declared.getRawType(); + if (registry.customCodec(rawType) != null + || registry.codecDeclaration(rawType) != null + || registry.hasSubTypes(rawType)) { + return null; + } + if (rawType.isArray()) { + codec = codec(declared.getComponentType().getType()); + return codec == null ? null : new SelectedCodec(null, codec, null, null); + } + if (rawType.getTypeParameters().length != 0 && !declared.hasExplicitTypeArguments()) { + return null; + } + if (Collection.class.isAssignableFrom(rawType) || rawType == AtomicReferenceArray.class) { + codec = codec(CodecUtils.elementTypeRef(declared).getType()); + return codec == null ? null : new SelectedCodec(null, codec, null, null); + } + if (rawType == Optional.class || rawType == AtomicReference.class) { + codec = codec(CodecUtils.elementTypeRef(declared).getType()); + return codec == null ? null : new SelectedCodec(null, null, codec, null); + } + if (Map.class.isAssignableFrom(rawType)) { + codec = codec(CodecUtils.mapKeyValueTypeRefs(declared).f1.getType()); + return codec == null ? null : new SelectedCodec(null, null, null, codec); + } + return null; + } + + private Class> codec(Type type) { + for (Entry entry : entries) { + if (sameType(entry.target, type)) { + return entry.codecClass; + } + } + return null; + } + + private static Entry find(List entries, Type target) { + for (Entry entry : entries) { + if (sameType(entry.target, target)) { + return entry; + } + } + return null; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static Type targetType( + Class declaring, Class> codecClass) { + if (codecClass == JsonCodec.NoJsonValueCodec.class) { + throw invalid(declaring, codecClass, "is not a codec"); + } + List> arguments = + ((TypeRef) TypeRef.of(codecClass)).getSupertype(JsonValueCodec.class).getTypeArguments(); + Type target = arguments.size() == 1 ? arguments.get(0).getType() : null; + if (target == null || !concrete(target)) { + throw invalid(declaring, codecClass, "does not declare a concrete value type"); + } + return target; + } + + private static boolean concrete(Type type) { + if (type instanceof Class) { + return true; + } + if (type instanceof ParameterizedType) { + ParameterizedType parameterized = (ParameterizedType) type; + if (!(parameterized.getRawType() instanceof Class)) { + return false; + } + for (Type argument : parameterized.getActualTypeArguments()) { + if (!concrete(argument)) { + return false; + } + } + return parameterized.getOwnerType() == null || concrete(parameterized.getOwnerType()); + } + if (type instanceof GenericArrayType) { + return concrete(((GenericArrayType) type).getGenericComponentType()); + } + return false; + } + + /** Compares reflected types structurally, independent of their implementation classes. */ + private static boolean sameType(Type a, Type b) { + if (a instanceof Class || b instanceof Class) { + return a.equals(b); + } + if (a instanceof ParameterizedType && b instanceof ParameterizedType) { + ParameterizedType left = (ParameterizedType) a; + ParameterizedType right = (ParameterizedType) b; + Type[] leftArguments = left.getActualTypeArguments(); + Type[] rightArguments = right.getActualTypeArguments(); + if (!left.getRawType().equals(right.getRawType()) + || leftArguments.length != rightArguments.length) { + return false; + } + for (int i = 0; i < leftArguments.length; i++) { + if (!sameType(leftArguments[i], rightArguments[i])) { + return false; + } + } + Type leftOwner = left.getOwnerType(); + Type rightOwner = right.getOwnerType(); + return leftOwner == null || rightOwner == null + ? Objects.equals(leftOwner, rightOwner) + : sameType(leftOwner, rightOwner); + } + if (a instanceof GenericArrayType && b instanceof GenericArrayType) { + return sameType( + ((GenericArrayType) a).getGenericComponentType(), + ((GenericArrayType) b).getGenericComponentType()); + } + return a.equals(b); + } + + private static ForyJsonException invalid(Class declaring, Class codecClass, String reason) { + return new ForyJsonException( + "Invalid @JsonDefaultCodec on " + + declaring.getName() + + ": " + + codecClass.getName() + + " " + + reason); + } + + private static final class Entry { + private final Type target; + private final Class> codecClass; + + private Entry(Type target, Class> codecClass) { + this.target = target; + this.codecClass = codecClass; + } + } + + /** {@link JsonCodec} configuration selected by a default rather than declared on a property. */ + private static final class SelectedCodec implements JsonCodec { + private final Class> value; + private final Class> elementCodec; + private final Class> contentCodec; + private final Class> valueCodec; + + private SelectedCodec( + Class> value, + Class> elementCodec, + Class> contentCodec, + Class> valueCodec) { + this.value = orNone(value); + this.elementCodec = orNone(elementCodec); + this.contentCodec = orNone(contentCodec); + this.valueCodec = orNone(valueCodec); + } + + private static Class> orNone( + Class> codec) { + return codec == null ? JsonCodec.NoJsonValueCodec.class : codec; + } + + @Override + public Class> value() { + return value; + } + + @Override + public Class> elementCodec() { + return elementCodec; + } + + @Override + public Class> contentCodec() { + return contentCodec; + } + + @Override + public Class keyCodec() { + return JsonCodec.NoMapKeyCodec.class; + } + + @Override + public Class> valueCodec() { + return valueCodec; + } + + @Override + public Class annotationType() { + return JsonCodec.class; + } + + // Annotation contract: equal to any JsonCodec with the same member values. + @Override + public boolean equals(Object other) { + if (!(other instanceof JsonCodec)) { + return false; + } + JsonCodec that = (JsonCodec) other; + return value == that.value() + && elementCodec == that.elementCodec() + && contentCodec == that.contentCodec() + && that.keyCodec() == JsonCodec.NoMapKeyCodec.class + && valueCodec == that.valueCodec(); + } + + @Override + public int hashCode() { + return member("value", value) + + member("elementCodec", elementCodec) + + member("contentCodec", contentCodec) + + member("keyCodec", JsonCodec.NoMapKeyCodec.class) + + member("valueCodec", valueCodec); + } + + private static int member(String name, Class value) { + return (127 * name.hashCode()) ^ value.hashCode(); + } + + @Override + public String toString() { + return "@JsonDefaultCodec selection " + + Arrays.asList(value, elementCodec, contentCodec, valueCodec); + } + } +} 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..eeb41a8d85 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 @@ -48,6 +48,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.JsonDefaultCodec; import org.apache.fory.json.annotation.JsonDuplicateProperties; import org.apache.fory.json.annotation.JsonFormat; import org.apache.fory.json.annotation.JsonIgnore; @@ -74,6 +75,8 @@ final class JsonMixinAnnotations { JsonByteArray.class, JsonCodec.class, JsonCreator.class, + JsonDefaultCodec.class, + JsonDefaultCodec.List.class, JsonDuplicateProperties.class, JsonFormat.class, JsonIgnore.class, diff --git a/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java b/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java index 50ece8e126..7f036f333b 100644 --- a/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java +++ b/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java @@ -53,6 +53,7 @@ import org.apache.fory.json.annotation.JsonAnySetter; import org.apache.fory.json.annotation.JsonByteArray; import org.apache.fory.json.annotation.JsonCodec; +import org.apache.fory.json.annotation.JsonDefaultCodec; import org.apache.fory.json.annotation.JsonCreator; import org.apache.fory.json.annotation.JsonMixin; import org.apache.fory.json.annotation.JsonSubTypes; @@ -585,6 +586,14 @@ private boolean registerMixin( registerDeclarations(targetType); JsonCodec directTypeCodec = annotations.annotation(targetType, JsonCodec.class); registerCodecs(directTypeCodec); + registerDefaultCodecs(annotations.annotation(targetType, JsonDefaultCodec.class)); + JsonDefaultCodec.List defaultCodecs = + annotations.annotation(targetType, JsonDefaultCodec.List.class); + if (defaultCodecs != null) { + for (JsonDefaultCodec defaults : defaultCodecs.value()) { + registerDefaultCodecs(defaults); + } + } RuntimeReflection.register(targetType); registerContainer(targetType); boolean intrinsicTarget = @@ -995,6 +1004,11 @@ private boolean registerDeclarations(Class type) { registerCodecs(annotation); changed = true; } + for (JsonDefaultCodec defaults : type.getDeclaredAnnotationsByType(JsonDefaultCodec.class)) { + RuntimeReflection.register(type); + registerDefaultCodecs(defaults); + changed = true; + } changed |= registerDeclarations(type.getSuperclass()); for (Class interfaceType : type.getInterfaces()) { changed |= registerDeclarations(interfaceType); @@ -1098,6 +1112,15 @@ private void registerCodecs(JsonCodec annotation) { registerCodec(annotation.valueCodec()); } + private void registerDefaultCodecs(JsonDefaultCodec annotation) { + if (annotation == null) { + return; + } + for (Class codecClass : annotation.value()) { + registerCodec(codecClass); + } + } + private void registerCodec(Class codecClass) { if (codecClass == JsonCodec.NoJsonValueCodec.class || codecClass == JsonCodec.NoMapKeyCodec.class) { diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java new file mode 100644 index 0000000000..9d2818538c --- /dev/null +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -0,0 +1,415 @@ +/* + * 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.assertTrue; +import static org.testng.Assert.expectThrows; + +import java.math.BigDecimal; +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.concurrent.atomic.AtomicReference; +import org.apache.fory.json.annotation.JsonCodec; +import org.apache.fory.json.annotation.JsonCreator; +import org.apache.fory.json.annotation.JsonDefaultCodec; +import org.apache.fory.json.annotation.JsonMixin; +import org.apache.fory.json.annotation.JsonProperty; +import org.apache.fory.json.codec.AbstractJsonValueCodec; +import org.apache.fory.json.reader.JsonReader; +import org.apache.fory.json.writer.JsonWriter; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; + +public class JsonDefaultCodecTest extends ForyJsonTestModels { + private static final BigDecimal TEN = new BigDecimal("1E+1"); + // Plain notation reads back with scale 0, which BigDecimal.equals distinguishes from 1E+1. + private static final BigDecimal PLAIN_TEN = new BigDecimal("10"); + + @Factory(dataProvider = "enableCodegen") + public JsonDefaultCodecTest(boolean codegen) { + super(codegen); + } + + /** Writes a decimal as a tagged plain-notation string so both directions are observable. */ + public static final class TaggedDecimalCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, BigDecimal value) { + writer.writeString("d:" + value.toPlainString()); + } + + @Override + public BigDecimal read(JsonReader reader) { + String text = reader.readString(); + if (!text.startsWith("d:")) { + throw new ForyJsonException("Untagged decimal " + text); + } + return new BigDecimal(text.substring(2)); + } + } + + public static final class OtherDecimalCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, BigDecimal value) { + writer.writeString("o:" + value.toPlainString()); + } + + @Override + public BigDecimal read(JsonReader reader) { + return new BigDecimal(reader.readString().substring(2)); + } + } + + public static final class TaggedOptionalCodec + extends AbstractJsonValueCodec> { + @Override + public void write(JsonWriter writer, Optional value) { + writer.writeString("od:" + value.get().toPlainString()); + } + + @Override + public Optional read(JsonReader reader) { + return Optional.of(new BigDecimal(reader.readString().substring(3))); + } + } + + public static final class TaggedIntegerCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, Integer value) { + writer.writeString("i:" + value); + } + + @Override + public Integer read(JsonReader reader) { + return Integer.valueOf(reader.readString().substring(2)); + } + } + + public static final class WildcardListCodec extends AbstractJsonValueCodec> { + @Override + public void write(JsonWriter writer, List value) { + writer.writeNull(); + } + + @Override + public List read(JsonReader reader) { + return null; + } + } + + @JsonDefaultCodec(TaggedDecimalCodec.class) + public static class Prices { + public BigDecimal price; + public Optional bid = Optional.empty(); + public List floors; + public BigDecimal[] steps; + public Map byCurrency; + public AtomicReference last; + public String name; + + @JsonCodec(OtherDecimalCodec.class) + public BigDecimal explicit; + + public Nested nested; + } + + public static class Nested { + public BigDecimal value; + } + + @Test + public void selectsWholeValueAndDirectChildren() { + ForyJson json = newJson(); + Prices prices = new Prices(); + prices.price = TEN; + prices.bid = Optional.of(TEN); + prices.floors = Arrays.asList(TEN, BigDecimal.ONE); + prices.steps = new BigDecimal[] {TEN}; + prices.byCurrency = Collections.singletonMap("USD", TEN); + prices.last = new AtomicReference<>(TEN); + prices.name = "p"; + prices.explicit = TEN; + prices.nested = new Nested(); + prices.nested.value = TEN; + String text = json.toJson(prices); + assertEquals( + text, + "{\"price\":\"d:10\",\"bid\":\"d:10\",\"floors\":[\"d:10\",\"d:1\"],\"steps\":[\"d:10\"]," + + "\"byCurrency\":{\"USD\":\"d:10\"},\"last\":\"d:10\",\"name\":\"p\"," + + "\"explicit\":\"o:10\",\"nested\":{\"value\":1E+1}}"); + for (Prices read : + Arrays.asList( + json.fromJson(text, Prices.class), + json.fromJson(text.getBytes(StandardCharsets.UTF_8), Prices.class))) { + assertEquals(read.price, PLAIN_TEN); + assertEquals(read.bid, Optional.of(PLAIN_TEN)); + assertEquals(read.floors, Arrays.asList(PLAIN_TEN, BigDecimal.ONE)); + assertEquals(read.steps, new BigDecimal[] {PLAIN_TEN}); + assertEquals(read.byCurrency, Collections.singletonMap("USD", PLAIN_TEN)); + assertEquals(read.last.get(), PLAIN_TEN); + assertEquals(read.explicit, PLAIN_TEN); + assertEquals(read.nested.value, TEN); + } + // The tagged reader proves the default codec, not the built-in decimal mapping, reads it. + expectThrows(ForyJsonException.class, () -> json.fromJson("{\"price\":\"10\"}", Prices.class)); + } + + @JsonDefaultCodec({TaggedDecimalCodec.class, TaggedOptionalCodec.class}) + public static class ListForm { + public BigDecimal price; + public Optional bid = Optional.empty(); + } + + @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(TaggedOptionalCodec.class) + public static class RepeatedForm { + public BigDecimal price; + public Optional bid = Optional.empty(); + } + + @Test + public void listAndRepeatedFormsPreferExactParameterizedTarget() { + ForyJson json = newJson(); + ListForm list = new ListForm(); + list.price = TEN; + list.bid = Optional.of(TEN); + RepeatedForm repeated = new RepeatedForm(); + repeated.price = TEN; + repeated.bid = Optional.of(TEN); + String expected = "{\"price\":\"d:10\",\"bid\":\"od:10\"}"; + assertEquals(json.toJson(list), expected); + assertEquals(json.toJson(repeated), expected); + assertEquals(json.fromJson(expected, ListForm.class).bid, Optional.of(PLAIN_TEN)); + assertEquals(json.fromJson(expected, RepeatedForm.class).bid, Optional.of(PLAIN_TEN)); + } + + @JsonDefaultCodec(TaggedDecimalCodec.class) + public static class Base { + public BigDecimal inherited; + } + + public static class Child extends Base { + public BigDecimal own; + } + + @JsonDefaultCodec(OtherDecimalCodec.class) + public static class Overriding extends Base { + public BigDecimal own; + } + + @Test + public void superclassDefaultsApplyAndSubclassReplacesThem() { + ForyJson json = newJson(); + Child child = new Child(); + child.inherited = TEN; + child.own = TEN; + assertEquals(json.toJson(child), "{\"inherited\":\"d:10\",\"own\":\"d:10\"}"); + Overriding overriding = new Overriding(); + overriding.inherited = TEN; + overriding.own = TEN; + assertEquals(json.toJson(overriding), "{\"inherited\":\"o:10\",\"own\":\"o:10\"}"); + assertEquals(json.fromJson("{\"inherited\":\"o:10\"}", Overriding.class).inherited, PLAIN_TEN); + } + + @JsonDefaultCodec(TaggedDecimalCodec.class) + public static class Created { + private final BigDecimal price; + private final Optional bid; + + @JsonCreator + public Created( + @JsonProperty("price") BigDecimal price, + @JsonProperty("bid") Optional bid, + @JsonProperty("extra") BigDecimal extra) { + this.price = extra == null ? price : extra; + this.bid = bid; + } + + public BigDecimal getPrice() { + return price; + } + + public Optional getBid() { + return bid; + } + } + + @Test + public void creatorParameters() { + ForyJson json = newJson(); + Created created = json.fromJson("{\"price\":\"d:10\",\"bid\":\"d:1\"}", Created.class); + assertEquals(created.getPrice(), PLAIN_TEN); + assertEquals(created.getBid(), Optional.of(BigDecimal.ONE)); + // A creator-only parameter uses the class default as well. + assertEquals(json.fromJson("{\"extra\":\"d:10\"}", Created.class).getPrice(), PLAIN_TEN); + assertEquals( + json.toJson(new Created(TEN, Optional.of(TEN), null)), + "{\"price\":\"d:10\",\"bid\":\"d:10\"}"); + } + + @JsonDefaultCodec(TaggedIntegerCodec.class) + public static class Counts { + public int primitive; + public Integer boxed; + } + + @Test + public void primitiveMatchesItsWrapper() { + ForyJson json = newJson(); + Counts counts = new Counts(); + counts.primitive = 5; + counts.boxed = 6; + String text = json.toJson(counts); + assertEquals(text, "{\"primitive\":\"i:5\",\"boxed\":\"i:6\"}"); + Counts read = json.fromJson(text, Counts.class); + assertEquals(read.primitive, 5); + assertEquals(read.boxed, Integer.valueOf(6)); + } + + public static class Plain { + public BigDecimal price; + } + + @JsonMixin(target = Plain.class) + @JsonDefaultCodec(TaggedDecimalCodec.class) + public interface PlainMixin {} + + @Test + public void mixinSuppliesDefaults() { + ForyJson json = newJsonBuilder().registerMixin(PlainMixin.class).build(); + Plain plain = new Plain(); + plain.price = TEN; + assertEquals(json.toJson(plain), "{\"price\":\"d:10\"}"); + assertEquals(json.fromJson("{\"price\":\"d:10\"}", Plain.class).price, PLAIN_TEN); + assertEquals(newJson().toJson(plain), "{\"price\":1E+1}"); + } + + @JsonMixin(target = RepeatedForm.class) + @JsonDefaultCodec(OtherDecimalCodec.class) + public interface RepeatedFormMixin {} + + @JsonMixin(target = ListForm.class) + @JsonDefaultCodec(OtherDecimalCodec.class) + @JsonDefaultCodec(TaggedOptionalCodec.class) + public interface ListFormMixin {} + + @Test + public void mixinReplacesBothDeclarationForms() { + ForyJson json = + newJsonBuilder() + .registerMixin(RepeatedFormMixin.class) + .registerMixin(ListFormMixin.class) + .build(); + RepeatedForm repeated = new RepeatedForm(); + repeated.price = TEN; + repeated.bid = Optional.of(TEN); + // The single Mixin declaration replaces the target's repeated ones, Optional + // included. + assertEquals(json.toJson(repeated), "{\"price\":\"o:10\",\"bid\":\"o:10\"}"); + ListForm list = new ListForm(); + list.price = TEN; + list.bid = Optional.of(TEN); + assertEquals(json.toJson(list), "{\"price\":\"o:10\",\"bid\":\"od:10\"}"); + } + + /** Owns its whole representation, so its elements are not a child slot a default can fill. */ + public static final class DecimalBagCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, DecimalBag value) { + writer.writeString("bag:" + value.size()); + } + + @Override + public DecimalBag read(JsonReader reader) { + reader.readString(); + return new DecimalBag(); + } + } + + @JsonCodec(DecimalBagCodec.class) + public static class DecimalBag extends java.util.ArrayList {} + + @JsonDefaultCodec(TaggedDecimalCodec.class) + public static class WithBag { + public DecimalBag bag; + public List registered; + } + + @Test + public void completeContainerCodecHidesChildDefault() { + ForyJson json = + newJsonBuilder() + .registerCodec( + List.class, + new AbstractJsonValueCodec() { + @Override + public void write(JsonWriter writer, List value) { + writer.writeString("list:" + value.size()); + } + + @Override + public List read(JsonReader reader) { + reader.readString(); + return Collections.emptyList(); + } + }) + .build(); + WithBag value = new WithBag(); + value.bag = new DecimalBag(); + value.bag.add(TEN); + value.registered = Collections.singletonList(TEN); + assertEquals(json.toJson(value), "{\"bag\":\"bag:1\",\"registered\":\"list:1\"}"); + } + + @JsonDefaultCodec({TaggedDecimalCodec.class, OtherDecimalCodec.class}) + public static class DuplicateTarget { + public BigDecimal price; + } + + @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(OtherDecimalCodec.class) + public static class RepeatedDuplicateTarget { + public BigDecimal price; + } + + @JsonDefaultCodec(WildcardListCodec.class) + public static class NoConcreteTarget { + public BigDecimal price; + } + + @Test + public void invalidDeclarations() { + ForyJson json = newJson(); + assertInvalid(json, DuplicateTarget.class, "Duplicate @JsonDefaultCodec target"); + assertInvalid(json, RepeatedDuplicateTarget.class, "Duplicate @JsonDefaultCodec target"); + assertInvalid(json, NoConcreteTarget.class, "does not declare a concrete value type"); + } + + private static void assertInvalid(ForyJson json, Class type, String message) { + ForyJsonException error = + expectThrows(ForyJsonException.class, () -> json.fromJson("{}", type)); + assertTrue( + String.valueOf(error.getMessage()).contains(message), String.valueOf(error.getMessage())); + } +} From effc85f39c2d17425b32d388b38bb59e26ebbdbc Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 21:06:04 +0100 Subject: [PATCH 02/26] fix(java): address review of class-level default codecs Co-Authored-By: Claude Opus 5.5 --- docs/json/custom-codecs.md | 18 ++- .../processing/JsonTypeProcessor.java | 7 +- .../processing/JsonTypeProcessorTest.java | 7 +- .../json/annotation/JsonDefaultCodec.java | 18 ++- .../fory/json/resolver/JsonDefaultCodecs.java | 56 ++++--- .../json/resolver/JsonMixinAnnotations.java | 7 + .../json/resolver/JsonSharedRegistry.java | 14 ++ .../fory/json/resolver/JsonTypeResolver.java | 17 ++ .../fory/json/JsonDefaultCodecTest.java | 152 ++++++++++++++++++ 9 files changed, 260 insertions(+), 36 deletions(-) diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index 98cfc2846d..ca34a3b3d6 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -295,18 +295,20 @@ several codecs in one annotation, `@JsonDefaultCodec({A.class, B.class})`, or re one class may name at most one codec per target type. A property or creator parameter whose resolved type equals a target uses the codec as if it -declared `@JsonCodec(value = ...)`; a primitive property matches its wrapper type. Otherwise a -target equal to the direct child of an array, `Collection`, `AtomicReferenceArray`, `Optional`, -`AtomicReference`, or the value of a `Map` fills the matching child member from the table above. -Deeper nesting is not searched. A child that a complete codec of its container hides is left -unchanged instead of failing. +declared `@JsonCodec(value = ...)`; a primitive property or array element matches its wrapper type. +Otherwise a target equal to the direct child of an array, `Collection`, `AtomicReferenceArray`, +`Optional`, `AtomicReference`, or the value of a `Map` fills the matching child member from the +table above. Deeper nesting is not searched. A child is filled only where the container keeps its +standard mapping: a registered codec or factory, a module, or a type declaration that owns the +container keeps it unchanged. Properties that declare `JsonCodec`, `JsonFormat`, `JsonByteArray`, `JsonRawValue`, or `JsonUnwrapped`, and JSON Any properties, do not use defaults. Defaults declared on superclasses apply to the subclass, and a subclass default for the same target type replaces the inherited one. -Defaults stop at the class boundary: a nested object type uses its own declarations. An -exact-target Mixin may supply or replace the annotation; a Mixin that supplies or removes either -the single or the repeated form replaces both forms declared on the target. +A declaration on an interface is rejected. Defaults stop at the class boundary: a nested object +type uses its own declarations. An exact-target Mixin may supply or replace the annotation; a Mixin +that supplies or removes either the single or the repeated form replaces both forms declared on the +target, and a removal also drops the defaults inherited from superclasses. ### Kotlin occurrences diff --git a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java index 40f3abe643..62b9afd1bf 100644 --- a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java +++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java @@ -720,9 +720,14 @@ private String writeR8(Model model) { } } for (String annotationType : model.annotationTypes) { + // Keep rules name nested annotation types by binary name, such as JsonDefaultCodec$List. + TypeElement annotationElement = elements.getTypeElement(annotationType); builder .append("-keep,allowoptimization,allowobfuscation @interface ") - .append(annotationType) + .append( + annotationElement == null + ? annotationType + : elements.getBinaryName(annotationElement).toString()) .append("\n"); } for (String container : model.containerTypes) { diff --git a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java index fca1d225e3..c4154b9b83 100644 --- a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java +++ b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java @@ -1663,7 +1663,12 @@ public void defaultCodecRules() throws Exception { assertTrue( rules.contains("class test.DefaultCodecModel$OptionalCodec { public (); }"), rules); assertTrue(rules.contains("class test.DefaultCodecBase$BaseCodec { public (); }"), rules); - assertTrue(rules.contains("org.apache.fory.json.annotation.JsonDefaultCodec"), rules); + // The model itself uses only the repeated form, compiled into the nested container. + String keep = "-keep,allowoptimization,allowobfuscation @interface "; + assertTrue(rules.contains(keep + "org.apache.fory.json.annotation.JsonDefaultCodec\n"), rules); + assertTrue( + rules.contains(keep + "org.apache.fory.json.annotation.JsonDefaultCodec$List\n"), rules); + assertFalse(rules.contains("JsonDefaultCodec.List"), rules); } @Test diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java index 2702736263..4e9885a5e6 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java @@ -39,18 +39,20 @@ * and one class may name at most one codec per target type. * *

A property or creator parameter whose resolved type equals a target uses that codec as if it - * declared {@code @JsonCodec(value = ...)}; a primitive property matches its wrapper type. Without - * a whole-type match, a target that equals the direct child of an array, {@code Collection}, {@code - * AtomicReferenceArray}, {@code Optional}, {@code AtomicReference}, or the value of a {@code Map} - * is used as the matching {@link JsonCodec} child member. A child that a complete codec of its - * container would hide is left unchanged. + * declared {@code @JsonCodec(value = ...)}; a primitive property or array element matches its + * wrapper type. Without a whole-type match, a target that equals the direct child of an array, + * {@code Collection}, {@code AtomicReferenceArray}, {@code Optional}, {@code AtomicReference}, or + * the value of a {@code Map} is used as the matching {@link JsonCodec} child member, but only where + * the container keeps its standard mapping: a registered codec or factory, a module, or a type + * declaration that owns the container keeps it unchanged. * *

A property that declares its own {@link JsonCodec}, {@link JsonFormat}, {@link JsonByteArray}, * {@link JsonRawValue}, or {@link JsonUnwrapped}, and JSON Any properties, do not use defaults. * Defaults declared on superclasses apply too, and a subclass default for the same target type - * replaces the inherited one. Defaults do not reach nested object types, which use their own class - * declarations. An exact-target {@link JsonMixin} may supply or replace this annotation; supplying - * or removing either the single or the repeated form replaces both forms declared on the target. + * replaces the inherited one. Declarations on interfaces are rejected. Defaults do not reach nested + * object types, which use their own class declarations. An exact-target {@link JsonMixin} may + * supply or replace this annotation; supplying or removing either the single or the repeated form + * replaces both forms declared on the target, and a removal also drops inherited defaults. */ @Documented @Retention(RetentionPolicy.RUNTIME) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 6e991cf2f0..4ef29f4bd3 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -49,34 +49,33 @@ */ @Internal public final class JsonDefaultCodecs { - private static final JsonDefaultCodecs NONE = new JsonDefaultCodecs(null, new Entry[0]); + private static final JsonDefaultCodecs NONE = new JsonDefaultCodecs(new Entry[0]); - private final JsonSharedRegistry registry; private final Entry[] entries; - private JsonDefaultCodecs(JsonSharedRegistry registry, Entry[] entries) { - this.registry = registry; + private JsonDefaultCodecs(Entry[] entries) { this.entries = entries; } /** Collects the defaults of {@code type}; a subclass entry replaces a superclass one. */ public static JsonDefaultCodecs of(Class type, JsonSharedRegistry registry) { + // Like a type-level JsonCodec, a Mixin removal on the target also drops inherited defaults. + boolean inherit = + !registry.mixinRemoves(type, type, JsonDefaultCodec.class) + && !registry.mixinRemoves(type, type, JsonDefaultCodec.List.class); List entries = null; for (Class declaring = type; - declaring != null && declaring != Object.class; + declaring != null && declaring != Object.class && (inherit || declaring == type); declaring = declaring.getSuperclass()) { + rejectInterfaceDeclarations(type, declaring.getInterfaces(), registry); JsonDefaultCodec single = registry.annotation(type, declaring, JsonDefaultCodec.class); JsonDefaultCodec.List repeated = registry.annotation(type, declaring, JsonDefaultCodec.List.class); // Java stores repeated declarations in the container, so a Mixin that supplies or removes // either form replaces both forms declared on the target. - boolean singleReplaced = - !Objects.equals( - single, JsonMixinAnnotations.targetAnnotation(declaring, JsonDefaultCodec.class)); + boolean singleReplaced = registry.mixinOverrides(type, declaring, JsonDefaultCodec.class); boolean repeatedReplaced = - !Objects.equals( - repeated, - JsonMixinAnnotations.targetAnnotation(declaring, JsonDefaultCodec.List.class)); + registry.mixinOverrides(type, declaring, JsonDefaultCodec.List.class); if (singleReplaced && !repeatedReplaced) { repeated = null; } else if (repeatedReplaced && !singleReplaced) { @@ -116,7 +115,23 @@ public static JsonDefaultCodecs of(Class type, JsonSharedRegistry registry) { } } } - return entries == null ? NONE : new JsonDefaultCodecs(registry, entries.toArray(new Entry[0])); + return entries == null ? NONE : new JsonDefaultCodecs(entries.toArray(new Entry[0])); + } + + /** Interface defaults would need a merge order across unrelated interfaces, so they fail. */ + private static void rejectInterfaceDeclarations( + Class type, Class[] interfaces, JsonSharedRegistry registry) { + for (Class interfaceType : interfaces) { + if (registry.annotation(type, interfaceType, JsonDefaultCodec.class) != null + || registry.annotation(type, interfaceType, JsonDefaultCodec.List.class) != null) { + throw new ForyJsonException( + "@JsonDefaultCodec is read from classes only, not from interface " + + interfaceType.getName() + + " of " + + type.getName()); + } + rejectInterfaceDeclarations(type, interfaceType.getInterfaces(), registry); + } } public boolean isEmpty() { @@ -134,13 +149,9 @@ public JsonCodec select(TypeRef type) { return new SelectedCodec(codec, null, null, null); } Class rawType = declared.getRawType(); - if (registry.customCodec(rawType) != null - || registry.codecDeclaration(rawType) != null - || registry.hasSubTypes(rawType)) { - return null; - } if (rawType.isArray()) { - codec = codec(declared.getComponentType().getType()); + TypeRef component = declared.getComponentType(); + codec = codec((component.isPrimitive() ? component.wrap() : component).getType()); return codec == null ? null : new SelectedCodec(null, codec, null, null); } if (rawType.getTypeParameters().length != 0 && !declared.hasExplicitTypeArguments()) { @@ -161,6 +172,15 @@ public JsonCodec select(TypeRef type) { return null; } + /** + * Returns whether {@code annotation} is a default that fills a child member. The resolver keeps + * the container's own mapping when it is not the standard container representation. + */ + static boolean selectsChild(JsonCodec annotation) { + return annotation instanceof SelectedCodec + && annotation.value() == JsonCodec.NoJsonValueCodec.class; + } + private Class> codec(Type type) { for (Entry entry : entries) { if (sameType(entry.target, type)) { 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 eeb41a8d85..1b5889a9e4 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 @@ -514,6 +514,13 @@ boolean removed(AnnotatedElement target, Class annotationT ElementOverlay overlay = declarations.get(target); return overlay != null && overlay.removals.contains(annotationType); } + + boolean overrides(AnnotatedElement target, Class annotationType) { + ElementOverlay overlay = declarations.get(target); + return overlay != null + && (overlay.replacements.containsKey(annotationType) + || overlay.removals.contains(annotationType)); + } } private static final class ElementOverlay { 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..5e15ea55b1 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 @@ -1270,6 +1270,20 @@ public A annotation( : overlay.annotation(declaration, annotationType); } + /** Returns whether the target's Mixin removes this annotation from the declaration. */ + boolean mixinRemoves( + Class targetType, AnnotatedElement declaration, Class type) { + JsonMixinAnnotations.TargetOverlay overlay = mixinAnnotations.overlay(targetType); + return overlay != null && overlay.removed(declaration, type); + } + + /** Returns whether the target's Mixin supplies or removes this annotation on the declaration. */ + boolean mixinOverrides( + Class targetType, AnnotatedElement declaration, Class type) { + JsonMixinAnnotations.TargetOverlay overlay = mixinAnnotations.overlay(targetType); + return overlay != null && overlay.overrides(declaration, type); + } + Class mixinType(Class targetType) { JsonMixinAnnotations.TargetOverlay overlay = mixinAnnotations.overlay(targetType); return overlay == null ? null : overlay.mixinType(); 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..90e511e706 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 @@ -419,6 +419,14 @@ public JsonTypeInfo getTypeInfo(TypeRef declaredType, JsonCodec annotation) { if (annotation == null) { return getTypeInfo(declaredType); } + if (JsonDefaultCodecs.selectsChild(annotation)) { + // A class default fills a child only where the container keeps its standard mapping, so a + // registration, factory, module, or type declaration that owns the container still wins. + JsonTypeInfo container = getTypeInfo(declaredType); + if (!standardContainer(container.valueCodec())) { + return container; + } + } ResolutionSnapshot snapshot = beginResolution(); try { JsonTypeInfo result = resolveTypeInfo(declaredType, annotation); @@ -795,6 +803,15 @@ private void validateCovariant(TypeRef type) { } } + private static boolean standardContainer(JsonValueCodec codec) { + return codec instanceof ArrayCodec + || codec instanceof CollectionCodec + || codec instanceof MapCodec + || codec instanceof ScalarCodecs.OptionalCodec + || codec instanceof ScalarCodecs.AtomicReferenceCodec + || codec instanceof ScalarCodecs.AtomicReferenceArrayCodec; + } + private static TypeRef directElementType(TypeRef typeRef, Class rawType, String slot) { return directElementType(typeRef, rawType, slot, "@JsonCodec"); } diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index 9d2818538c..fb95987660 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -34,7 +34,9 @@ import org.apache.fory.json.annotation.JsonCodec; import org.apache.fory.json.annotation.JsonCreator; import org.apache.fory.json.annotation.JsonDefaultCodec; +import org.apache.fory.json.annotation.JsonFormat; import org.apache.fory.json.annotation.JsonMixin; +import org.apache.fory.json.annotation.JsonMixinRemove; import org.apache.fory.json.annotation.JsonProperty; import org.apache.fory.json.codec.AbstractJsonValueCodec; import org.apache.fory.json.reader.JsonReader; @@ -382,6 +384,155 @@ public List read(JsonReader reader) { assertEquals(json.toJson(value), "{\"bag\":\"bag:1\",\"registered\":\"list:1\"}"); } + @JsonDefaultCodec(TaggedDecimalCodec.class) + public static class WithList { + public List values; + } + + @Test + public void containerFactoryKeepsItsRepresentation() { + AbstractJsonValueCodec> listCodec = + new AbstractJsonValueCodec>() { + @Override + public void write(JsonWriter writer, List value) { + writer.writeString("factory:" + value.size()); + } + + @Override + public List read(JsonReader reader) { + reader.readString(); + return Collections.emptyList(); + } + }; + JsonCodecFactory factory = + (type, resolver, runtimeType) -> type.getRawType() == List.class ? listCodec : null; + WithList value = new WithList(); + value.values = Collections.singletonList(TEN); + ForyJson exact = newJsonBuilder().registerCodec(List.class, factory).build(); + ForyJson module = + newJsonBuilder().withModule(context -> context.registerCodecFactory(factory)).build(); + assertEquals(exact.toJson(value), "{\"values\":\"factory:1\"}"); + assertEquals(module.toJson(value), "{\"values\":\"factory:1\"}"); + } + + @JsonDefaultCodec(TaggedIntegerCodec.class) + public static class IntArrays { + public int[] primitive; + public Integer[] boxed; + } + + @Test + public void primitiveArrayElementsMatchTheirWrapper() { + ForyJson json = newJson(); + IntArrays value = new IntArrays(); + value.primitive = new int[] {1, 2}; + value.boxed = new Integer[] {3}; + String text = json.toJson(value); + assertEquals(text, "{\"primitive\":[\"i:1\",\"i:2\"],\"boxed\":[\"i:3\"]}"); + IntArrays read = json.fromJson(text, IntArrays.class); + assertEquals(read.primitive, new int[] {1, 2}); + assertEquals(read.boxed, new Integer[] {3}); + } + + @JsonMixin(target = RepeatedForm.class) + @JsonMixinRemove(JsonDefaultCodec.class) + public interface RemoveSingleFromRepeated {} + + @JsonMixin(target = ListForm.class) + @JsonMixinRemove(JsonDefaultCodec.List.class) + public interface RemoveRepeatedFromSingle {} + + @Test + public void mixinRemovalClearsBothDeclarationForms() { + ForyJson json = + newJsonBuilder() + .registerMixin(RemoveSingleFromRepeated.class) + .registerMixin(RemoveRepeatedFromSingle.class) + .build(); + RepeatedForm repeated = new RepeatedForm(); + repeated.price = TEN; + ListForm list = new ListForm(); + list.price = TEN; + // An empty Optional without a codec keeps Fory's default null form. + assertEquals(json.toJson(repeated), "{\"price\":1E+1,\"bid\":null}"); + assertEquals(json.toJson(list), "{\"price\":1E+1,\"bid\":null}"); + } + + @JsonMixin(target = Child.class) + @JsonMixinRemove(JsonDefaultCodec.class) + public interface ChildWithoutDefaults {} + + @Test + public void mixinRemovalOnTargetDropsInheritedDefaults() { + ForyJson json = newJsonBuilder().registerMixin(ChildWithoutDefaults.class).build(); + Child child = new Child(); + child.inherited = TEN; + child.own = TEN; + assertEquals(json.toJson(child), "{\"inherited\":1E+1,\"own\":1E+1}"); + Base base = new Base(); + base.inherited = TEN; + assertEquals(json.toJson(base), "{\"inherited\":\"d:10\"}"); + } + + @JsonDefaultCodec(TaggedDecimalCodec.class) + public static class Box { + public T value; + public List values; + } + + public static class Holder { + public Box decimals; + public Box strings; + } + + @Test + public void typeVariablesMatchAfterResolution() { + ForyJson json = newJson(); + Holder holder = new Holder(); + holder.decimals = new Box<>(); + holder.decimals.value = TEN; + holder.decimals.values = Collections.singletonList(TEN); + holder.strings = new Box<>(); + holder.strings.value = "s"; + String text = json.toJson(holder); + assertEquals( + text, + "{\"decimals\":{\"value\":\"d:10\",\"values\":[\"d:10\"]}," + + "\"strings\":{\"value\":\"s\"}}"); + Holder read = json.fromJson(text, Holder.class); + assertEquals(read.decimals.value, PLAIN_TEN); + assertEquals(read.decimals.values, Collections.singletonList(PLAIN_TEN)); + assertEquals(read.strings.value, "s"); + } + + @JsonDefaultCodec(TaggedDecimalCodec.class) + public static class FormattedCreator { + private final BigDecimal price; + + @JsonCreator + public FormattedCreator( + @JsonProperty("price") @JsonFormat(shape = JsonFormat.Shape.STRING) BigDecimal price) { + this.price = price; + } + + public BigDecimal price() { + return price; + } + } + + @Test + public void declaredFormatOnCreatorParameterWins() { + ForyJson json = newJson(); + assertEquals(json.fromJson("{\"price\":\"10\"}", FormattedCreator.class).price(), PLAIN_TEN); + } + + @JsonDefaultCodec(TaggedDecimalCodec.class) + public interface DefaultsOnInterface {} + + public static class ImplementsDefaults implements DefaultsOnInterface { + public BigDecimal price; + } + @JsonDefaultCodec({TaggedDecimalCodec.class, OtherDecimalCodec.class}) public static class DuplicateTarget { public BigDecimal price; @@ -404,6 +555,7 @@ public void invalidDeclarations() { assertInvalid(json, DuplicateTarget.class, "Duplicate @JsonDefaultCodec target"); assertInvalid(json, RepeatedDuplicateTarget.class, "Duplicate @JsonDefaultCodec target"); assertInvalid(json, NoConcreteTarget.class, "does not declare a concrete value type"); + assertInvalid(json, ImplementsDefaults.class, "not from interface"); } private static void assertInvalid(ForyJson json, Class type, String message) { From bb1d11496f28d441d1c4ea8d2d4a95d0f039eae5 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 21:19:50 +0100 Subject: [PATCH 03/26] fix(java): resolve default child codecs without the container's ordinary mapping Co-Authored-By: Claude Opus 5.5 --- docs/json/custom-codecs.md | 3 +- .../processing/JsonTypeProcessorTest.java | 42 +++++ .../json/resolver/JsonSharedRegistry.java | 23 +++ .../fory/json/resolver/JsonTypeResolver.java | 21 +-- .../fory/json/JsonDefaultCodecTest.java | 170 ++++++++++++++++++ 5 files changed, 242 insertions(+), 17 deletions(-) diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index ca34a3b3d6..fe4ab14691 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -298,7 +298,8 @@ A property or creator parameter whose resolved type equals a target uses the cod declared `@JsonCodec(value = ...)`; a primitive property or array element matches its wrapper type. Otherwise a target equal to the direct child of an array, `Collection`, `AtomicReferenceArray`, `Optional`, `AtomicReference`, or the value of a `Map` fills the matching child member from the -table above. Deeper nesting is not searched. A child is filled only where the container keeps its +table above, so a `Byte` default writes a `byte[]` as a JSON array of codec values whatever +`byteArrayFormat` says. Deeper nesting is not searched. A child is filled only where the container keeps its standard mapping: a registered codec or factory, a module, or a type declaration that owns the container keeps it unchanged. diff --git a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java index c4154b9b83..d1d9fe2ba8 100644 --- a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java +++ b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java @@ -32,6 +32,7 @@ import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.math.BigDecimal; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; @@ -44,6 +45,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaCompiler; @@ -1617,6 +1619,46 @@ public void codecMemberRules() throws Exception { assertTrue(rules.contains("class java.util.HashMap { public (); }"), rules); } + @Test + public void defaultCodecRecordPipeline() throws Exception { + assumeJava16Source(); + CompilationResult result = + compile( + "test.DefaultCodecRecord", + "package test;\n" + + "import java.math.BigDecimal;\n" + + "import java.util.Optional;\n" + + "import org.apache.fory.json.annotation.*;\n" + + "@JsonType @JsonDefaultCodec(DefaultCodecRecord.Plain.class)\n" + + "public record DefaultCodecRecord(BigDecimal price, Optional bid) {\n" + + " public DefaultCodecRecord {\n" + + " bid = bid == null ? Optional.empty() : bid;\n" + + " }\n" + + " public static final class Plain\n" + + " extends org.apache.fory.json.codec.AbstractJsonValueCodec {\n" + + " public void write(org.apache.fory.json.writer.JsonWriter w, BigDecimal v) {\n" + + " w.writeString(\"p:\" + v.toPlainString());\n" + + " }\n" + + " public BigDecimal read(org.apache.fory.json.reader.JsonReader r) {\n" + + " return new BigDecimal(r.readString().substring(2));\n" + + " }\n" + + " }\n" + + "}\n"); + assertTrue(result.success, result.diagnostics()); + ClassLoader loader = result.classLoader(); + Class type = loader.loadClass("test.DefaultCodecRecord"); + BigDecimal ten = new BigDecimal("1E+1"); + Object value = + type.getConstructor(BigDecimal.class, Optional.class).newInstance(ten, Optional.of(ten)); + for (ForyJson json : jsonRuntimes(loader)) { + String text = json.toJson(value); + assertEquals(text, "{\"price\":\"p:10\",\"bid\":\"p:10\"}"); + Object decoded = json.fromJson(text, type); + assertEquals(type.getMethod("price").invoke(decoded), new BigDecimal("10")); + assertEquals(type.getMethod("bid").invoke(decoded), Optional.of(new BigDecimal("10"))); + } + } + @Test public void defaultCodecRules() throws Exception { String codec = 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 5e15ea55b1..e4c28f6bb6 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 @@ -1270,6 +1270,29 @@ public A annotation( : overlay.annotation(declaration, annotationType); } + /** + * Returns whether a representation other than the standard container mapping owns this container + * type. It follows {@link #resolveCodec} without resolving the container's children. + */ + boolean ownsContainer(TypeRef typeRef, JsonTypeResolver localResolver) { + Class rawType = typeRef.getRawType(); + if (hasRegisteredCodec(rawType) + || codecDeclaration(rawType) != null + || valueDeclaration(rawType) != null + || hasSubTypes(rawType) + || exactCodecs.get(rawType) != null) { + return true; + } + if (typeRef.getTypeExtMeta() != null && typeRef.getTypeExtMeta().typeId() != Types.UNKNOWN) { + return true; + } + if (!Collection.class.isAssignableFrom(rawType) && !Map.class.isAssignableFrom(rawType)) { + return false; + } + return codecFactories.length != 0 && createModuleCodec(typeRef, localResolver, false) != null + || inferredSubTypes(rawType); + } + /** Returns whether the target's Mixin removes this annotation from the declaration. */ boolean mixinRemoves( Class targetType, AnnotatedElement declaration, Class type) { 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 90e511e706..5b1b1df9b8 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 @@ -419,13 +419,11 @@ public JsonTypeInfo getTypeInfo(TypeRef declaredType, JsonCodec annotation) { if (annotation == null) { return getTypeInfo(declaredType); } - if (JsonDefaultCodecs.selectsChild(annotation)) { - // A class default fills a child only where the container keeps its standard mapping, so a - // registration, factory, module, or type declaration that owns the container still wins. - JsonTypeInfo container = getTypeInfo(declaredType); - if (!standardContainer(container.valueCodec())) { - return container; - } + // A class default fills a child only where the container keeps its standard mapping, so a + // registration, factory, module, or type declaration that owns the container still wins. + if (JsonDefaultCodecs.selectsChild(annotation) + && sharedRegistry.ownsContainer(declaredType, this)) { + return getTypeInfo(declaredType); } ResolutionSnapshot snapshot = beginResolution(); try { @@ -803,15 +801,6 @@ private void validateCovariant(TypeRef type) { } } - private static boolean standardContainer(JsonValueCodec codec) { - return codec instanceof ArrayCodec - || codec instanceof CollectionCodec - || codec instanceof MapCodec - || codec instanceof ScalarCodecs.OptionalCodec - || codec instanceof ScalarCodecs.AtomicReferenceCodec - || codec instanceof ScalarCodecs.AtomicReferenceArrayCodec; - } - private static TypeRef directElementType(TypeRef typeRef, Class rawType, String slot) { return directElementType(typeRef, rawType, slot, "@JsonCodec"); } diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index fb95987660..b061b27d91 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -533,6 +533,176 @@ public static class ImplementsDefaults implements DefaultsOnInterface { public BigDecimal price; } + public interface Shape { + String name(); + } + + public static final class ShapeCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, Shape value) { + writer.writeString("shape:" + value.name()); + } + + @Override + public Shape read(JsonReader reader) { + String name = reader.readString().substring(6); + return () -> name; + } + } + + @JsonDefaultCodec(ShapeCodec.class) + public static class Shapes { + public Shape single; + public List list; + public Optional optional = Optional.empty(); + public Shape[] array; + public Map map; + } + + @Test + public void interfaceChildWithoutOrdinaryMapping() { + ForyJson json = newJson(); + Shapes shapes = new Shapes(); + shapes.single = () -> "a"; + shapes.list = Collections.singletonList(() -> "b"); + shapes.optional = Optional.of(() -> "c"); + shapes.array = new Shape[] {() -> "d"}; + shapes.map = Collections.singletonMap("k", () -> "e"); + String text = json.toJson(shapes); + assertEquals( + text, + "{\"single\":\"shape:a\",\"list\":[\"shape:b\"],\"optional\":\"shape:c\"," + + "\"array\":[\"shape:d\"],\"map\":{\"k\":\"shape:e\"}}"); + Shapes read = json.fromJson(text, Shapes.class); + assertEquals(read.single.name(), "a"); + assertEquals(read.list.get(0).name(), "b"); + assertEquals(read.optional.get().name(), "c"); + assertEquals(read.array[0].name(), "d"); + assertEquals(read.map.get("k").name(), "e"); + } + + @JsonDefaultCodec(TaggedDecimalCodec.class) + public static class Shallow { + public List> nested; + public Map> nestedMap; + public java.util.concurrent.atomic.AtomicReferenceArray atomic; + } + + @Test + public void onlyDirectChildrenAndMapValuesAreDefaulted() { + ForyJson json = newJson(); + Shallow value = new Shallow(); + value.nested = Collections.singletonList(Optional.of(TEN)); + value.nestedMap = Collections.singletonMap("k", Collections.singletonList(TEN)); + value.atomic = new java.util.concurrent.atomic.AtomicReferenceArray<>(new BigDecimal[] {TEN}); + String text = json.toJson(value); + assertEquals( + text, "{\"nested\":[1E+1],\"nestedMap\":{\"k\":[1E+1]}," + "\"atomic\":[\"d:10\"]}"); + Shallow read = json.fromJson(text, Shallow.class); + assertEquals(read.atomic.get(0), PLAIN_TEN); + } + + @JsonDefaultCodec(TaggedIntegerCodec.class) + public static class Keyed { + public Map counts; + } + + @Test + public void mapKeysKeepTheirMapping() { + ForyJson json = newJson(); + Keyed value = new Keyed(); + value.counts = Collections.singletonMap(1, 2); + String text = json.toJson(value); + assertEquals(text, "{\"counts\":{\"1\":\"i:2\"}}"); + assertEquals(json.fromJson(text, Keyed.class).counts, Collections.singletonMap(1, 2)); + } + + @Test + public void contentNullSkipStillAppliesAroundChildDefault() { + ForyJson json = newJsonBuilder().onContentNullRead(JsonProperty.NullHandling.SKIP).build(); + Prices read = json.fromJson("{\"floors\":[\"d:1\",null]}", Prices.class); + assertEquals(read.floors, Collections.singletonList(BigDecimal.ONE)); + } + + /** Declares its value type through an intermediate generic superclass. */ + public abstract static class PrefixCodec extends AbstractJsonValueCodec {} + + public static final class InheritedDecimalCodec extends PrefixCodec { + @Override + public void write(JsonWriter writer, BigDecimal value) { + writer.writeString("x:" + value.toPlainString()); + } + + @Override + public BigDecimal read(JsonReader reader) { + return new BigDecimal(reader.readString().substring(2)); + } + } + + @JsonDefaultCodec(InheritedDecimalCodec.class) + public static class InheritedTarget { + public BigDecimal price; + } + + @Test + public void codecValueTypeResolvesThroughGenericSuperclass() { + InheritedTarget value = new InheritedTarget(); + value.price = TEN; + assertEquals(newJson().toJson(value), "{\"price\":\"x:10\"}"); + } + + @JsonDefaultCodec(TaggedIntegerCodec.class) + public static class MergedCreator { + private final int count; + + @JsonCreator + public MergedCreator(@JsonProperty("count") int count) { + this.count = count; + } + + public int getCount() { + return count; + } + } + + @Test + public void getterAndCreatorParameterShareTheDefault() { + ForyJson json = newJson(); + String text = json.toJson(new MergedCreator(7)); + assertEquals(text, "{\"count\":\"i:7\"}"); + assertEquals(json.fromJson(text, MergedCreator.class).getCount(), 7); + } + + @JsonDefaultCodec(TaggedByteCodec.class) + public static class Bytes { + public byte[] data; + } + + public static final class TaggedByteCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, Byte value) { + writer.writeString("b:" + value); + } + + @Override + public Byte read(JsonReader reader) { + return Byte.valueOf(reader.readString().substring(2)); + } + } + + @Test + public void byteArrayElementsUseDefaultInEveryByteArrayFormat() { + Bytes value = new Bytes(); + value.data = new byte[] {1, 2}; + for (org.apache.fory.json.annotation.JsonByteArray.Format format : + org.apache.fory.json.annotation.JsonByteArray.Format.values()) { + ForyJson json = newJsonBuilder().byteArrayFormat(format).build(); + String text = json.toJson(value); + assertEquals(text, "{\"data\":[\"b:1\",\"b:2\"]}", format.name()); + assertEquals(json.fromJson(text, Bytes.class).data, new byte[] {1, 2}); + } + } + @JsonDefaultCodec({TaggedDecimalCodec.class, OtherDecimalCodec.class}) public static class DuplicateTarget { public BigDecimal price; From cdc451db52d9ac564565182d1ca4c52e4171a13d Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 21:37:45 +0100 Subject: [PATCH 04/26] fix(java): keep semantic Kotlin types and codec supertypes for default codecs Co-Authored-By: Claude Opus 5.5 --- .../processing/JsonTypeProcessor.java | 23 +++++++++ .../processing/JsonTypeProcessorTest.java | 14 +++++- .../fory/json/resolver/JsonDefaultCodecs.java | 36 ++++++++++---- .../fory/json/ForyJsonGraalVMFeature.java | 18 ++++++- .../fory/json/JsonDefaultCodecTest.java | 49 +++++++++++++++++++ .../json/kotlin/KotlinBuiltInCodecsTest.kt | 30 ++++++++++++ 6 files changed, 159 insertions(+), 11 deletions(-) diff --git a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java index 62b9afd1bf..a8ba6a52e1 100644 --- a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java +++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java @@ -628,6 +628,25 @@ private void collectDefaultCodecs(AnnotationMirror annotation, Model model) { codecType instanceof TypeMirror ? asTypeElement((TypeMirror) codecType) : null; if (codec != null) { model.codecTypes.add(elements.getBinaryName(codec).toString()); + collectCodecSupertypes(codec, model); + } + } + } + + /** + * The runtime reads a default codec's target from the generic signatures of its supertypes, so a + * shrinker must neither drop nor merge the classes on the way to {@code JsonValueCodec}. + */ + private void collectCodecSupertypes(TypeElement type, Model model) { + List supertypes = new ArrayList<>(type.getInterfaces()); + supertypes.add(type.getSuperclass()); + for (TypeMirror supertype : supertypes) { + TypeElement element = asTypeElement(supertype); + if (element == null || element.getQualifiedName().toString().startsWith("java.")) { + continue; + } + if (model.codecSupertypes.add(elements.getBinaryName(element).toString())) { + collectCodecSupertypes(element, model); } } } @@ -730,6 +749,9 @@ private String writeR8(Model model) { : elements.getBinaryName(annotationElement).toString()) .append("\n"); } + for (String supertype : model.codecSupertypes) { + builder.append("-keep,allowoptimization class ").append(supertype).append("\n"); + } for (String container : model.containerTypes) { builder .append("-keep,allowoptimization,allowobfuscation class ") @@ -1460,6 +1482,7 @@ private static final class Model { final Set annotationTypes = new LinkedHashSet<>(); final Set containerTypes = new LinkedHashSet<>(); final Set codecTypes = new LinkedHashSet<>(); + final Set codecSupertypes = new LinkedHashSet<>(); final Set binaryFallbackTypes = new LinkedHashSet<>(); final Set annotationOwnerTypes = new LinkedHashSet<>(); final Set nameTypes = new LinkedHashSet<>(); diff --git a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java index d1d9fe2ba8..c33a9b97bb 100644 --- a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java +++ b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java @@ -1673,7 +1673,12 @@ public void defaultCodecRules() throws Exception { + "import org.apache.fory.json.annotation.JsonDefaultCodec;\n" + "@JsonDefaultCodec(DefaultCodecBase.BaseCodec.class)\n" + "public class DefaultCodecBase {\n" - + String.format(codec, "BaseCodec", "Long", "Long", "Long") + + " public abstract static class Prefix\n" + + " extends org.apache.fory.json.codec.AbstractJsonValueCodec {}\n" + + " public static final class BaseCodec extends Prefix {\n" + + " public void write(org.apache.fory.json.writer.JsonWriter writer, Long value) {}\n" + + " public Long read(org.apache.fory.json.reader.JsonReader reader) { return null; }\n" + + " }\n" + " public Long id;\n" + "}\n"); sources.put( @@ -1705,6 +1710,13 @@ public void defaultCodecRules() throws Exception { assertTrue( rules.contains("class test.DefaultCodecModel$OptionalCodec { public (); }"), rules); assertTrue(rules.contains("class test.DefaultCodecBase$BaseCodec { public (); }"), rules); + // The codec's target is read from the generic signature of its intermediate superclass. + assertTrue( + rules.contains("-keep,allowoptimization class test.DefaultCodecBase$Prefix\n"), rules); + assertTrue( + rules.contains( + "-keep,allowoptimization class org.apache.fory.json.codec.AbstractJsonValueCodec\n"), + rules); // The model itself uses only the repeated form, compiled into the nested container. String keep = "-keep,allowoptimization,allowobfuscation @interface "; assertTrue(rules.contains(keep + "org.apache.fory.json.annotation.JsonDefaultCodec\n"), rules); diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 4ef29f4bd3..652b682416 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -40,6 +40,7 @@ import org.apache.fory.json.codec.JsonValueCodec; import org.apache.fory.json.codec.MapKeyCodec; import org.apache.fory.reflect.TypeRef; +import org.apache.fory.type.Types; /** * Effective {@link JsonDefaultCodec} declarations of one object type and its superclasses. @@ -143,35 +144,52 @@ public JsonCodec select(TypeRef type) { if (entries.length == 0) { return null; } - TypeRef declared = type.isPrimitive() ? type.wrap() : type; - Class> codec = codec(declared.getType()); + Class> codec = codec(type); if (codec != null) { return new SelectedCodec(codec, null, null, null); } - Class rawType = declared.getRawType(); + if (semantic(type)) { + return null; + } + Class rawType = type.getRawType(); if (rawType.isArray()) { - TypeRef component = declared.getComponentType(); - codec = codec((component.isPrimitive() ? component.wrap() : component).getType()); + codec = codec(type.getComponentType()); return codec == null ? null : new SelectedCodec(null, codec, null, null); } - if (rawType.getTypeParameters().length != 0 && !declared.hasExplicitTypeArguments()) { + if (rawType.getTypeParameters().length != 0 && !type.hasExplicitTypeArguments()) { return null; } if (Collection.class.isAssignableFrom(rawType) || rawType == AtomicReferenceArray.class) { - codec = codec(CodecUtils.elementTypeRef(declared).getType()); + codec = codec(CodecUtils.elementTypeRef(type)); return codec == null ? null : new SelectedCodec(null, codec, null, null); } if (rawType == Optional.class || rawType == AtomicReference.class) { - codec = codec(CodecUtils.elementTypeRef(declared).getType()); + codec = codec(CodecUtils.elementTypeRef(type)); return codec == null ? null : new SelectedCodec(null, null, codec, null); } if (Map.class.isAssignableFrom(rawType)) { - codec = codec(CodecUtils.mapKeyValueTypeRefs(declared).f1.getType()); + codec = codec(CodecUtils.mapKeyValueTypeRefs(type).f1); return codec == null ? null : new SelectedCodec(null, null, null, codec); } return null; } + /** + * Returns the default for one occurrence. A primitive matches its wrapper, but a type a language + * module tags with its own semantic type, such as a Kotlin {@code UInt} carried as {@code int}, + * keeps that module's mapping. + */ + private Class> codec(TypeRef type) { + if (semantic(type)) { + return null; + } + return codec((type.isPrimitive() ? type.wrap() : type).getType()); + } + + private static boolean semantic(TypeRef type) { + return type.getTypeExtMeta() != null && type.getTypeExtMeta().typeId() != Types.UNKNOWN; + } + /** * Returns whether {@code annotation} is a default that fills a child member. The resolver keeps * the container's own mapping when it is not the standard container representation. diff --git a/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java b/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java index 7f036f333b..01771c29f4 100644 --- a/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java +++ b/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java @@ -53,8 +53,8 @@ import org.apache.fory.json.annotation.JsonAnySetter; import org.apache.fory.json.annotation.JsonByteArray; import org.apache.fory.json.annotation.JsonCodec; -import org.apache.fory.json.annotation.JsonDefaultCodec; import org.apache.fory.json.annotation.JsonCreator; +import org.apache.fory.json.annotation.JsonDefaultCodec; import org.apache.fory.json.annotation.JsonMixin; import org.apache.fory.json.annotation.JsonSubTypes; import org.apache.fory.json.annotation.JsonType; @@ -117,6 +117,7 @@ final class ForyJsonGraalVMFeature implements Feature { private final Set> scalaFactoryModels = ConcurrentHashMap.newKeySet(); private final Set> scalaEnumerationOwners = ConcurrentHashMap.newKeySet(); private final Set> processedCodecs = ConcurrentHashMap.newKeySet(); + private final Set> processedCodecSupertypes = ConcurrentHashMap.newKeySet(); private final Set> processedContainers = ConcurrentHashMap.newKeySet(); private final Set processedCreators = new LinkedHashSet<>(); // Reflection-only registrations are tracked apart from processedCreators, whose membership also @@ -1118,6 +1119,21 @@ private void registerDefaultCodecs(JsonDefaultCodec annotation) { } for (Class codecClass : annotation.value()) { registerCodec(codecClass); + registerCodecSupertypes(codecClass); + } + } + + /** The runtime reads a default codec's target from the generic signatures of its supertypes. */ + private void registerCodecSupertypes(Class type) { + List> supertypes = new ArrayList<>(Arrays.asList(type.getInterfaces())); + if (type.getSuperclass() != null) { + supertypes.add(type.getSuperclass()); + } + for (Class supertype : supertypes) { + if (supertype != Object.class && processedCodecSupertypes.add(supertype)) { + RuntimeReflection.register(supertype); + registerCodecSupertypes(supertype); + } } } diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index b061b27d91..d1760a5790 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -703,6 +703,55 @@ public void byteArrayElementsUseDefaultInEveryByteArrayFormat() { } } + public static final class TaggedStringCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, String value) { + writer.writeString("s:" + value); + } + + @Override + public String read(JsonReader reader) { + return reader.readString().substring(2); + } + } + + @JsonDefaultCodec({TaggedDecimalCodec.class, TaggedByteCodec.class, TaggedStringCodec.class}) + public static class Excluded { + @JsonFormat(shape = JsonFormat.Shape.STRING) + public BigDecimal formatted; + + @org.apache.fory.json.annotation.JsonByteArray( + org.apache.fory.json.annotation.JsonByteArray.Format.BASE16) + public byte[] bytes; + + @org.apache.fory.json.annotation.JsonRawValue public String raw; + + @org.apache.fory.json.annotation.JsonUnwrapped public Nested unwrapped; + + @org.apache.fory.json.annotation.JsonAnyProperty + public Map extra = new java.util.LinkedHashMap<>(); + } + + @Test + public void representationAnnotationsAndAnyValuesKeepTheirMapping() { + ForyJson json = newJson(); + Excluded value = new Excluded(); + value.formatted = TEN; + value.bytes = new byte[] {1, 2}; + value.raw = "{\"a\":1}"; + value.unwrapped = new Nested(); + value.unwrapped.value = TEN; + value.extra.put("x", TEN); + String text = json.toJson(value); + assertTrue(text.contains("\"formatted\":\"1E+1\""), text); + assertTrue(text.contains("\"bytes\":\"0102\""), text); + assertTrue(text.contains("\"raw\":{\"a\":1}"), text); + // The unwrapped Nested properties follow Nested's declarations, which have no default. + assertTrue(text.contains("\"value\":1E+1"), text); + assertTrue(text.contains("\"x\":1E+1"), text); + assertTrue(!text.contains("d:") && !text.contains("s:") && !text.contains("b:"), text); + } + @JsonDefaultCodec({TaggedDecimalCodec.class, OtherDecimalCodec.class}) public static class DuplicateTarget { public BigDecimal price; diff --git a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt index c823513b21..e2bda96425 100644 --- a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt +++ b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt @@ -37,6 +37,8 @@ import kotlin.uuid.ExperimentalUuidApi import kotlin.uuid.Uuid import org.apache.fory.json.ForyJsonException import org.apache.fory.json.annotation.JsonByteArray +import org.apache.fory.json.annotation.JsonDefaultCodec +import org.apache.fory.json.codec.AbstractJsonValueCodec import org.apache.fory.json.codec.DirectUnboxedValueCodec import org.apache.fory.json.reader.JsonReader import org.apache.fory.json.writer.JsonWriter @@ -88,6 +90,34 @@ class KotlinBuiltInCodecsTest { private val fory = ForyJsonKotlin.builder().withAsyncCompilation(false).build() + class TaggedIntCodec : AbstractJsonValueCodec() { + override fun write(writer: JsonWriter, value: Int) { + writer.writeString("i:$value") + } + + override fun read(reader: JsonReader): Int = reader.readString().substring(2).toInt() + } + + @JsonDefaultCodec(TaggedIntCodec::class) + data class SignedAndUnsigned( + val signed: Int, + val unsigned: UInt, + val signedList: List, + val unsignedList: List, + ) + + @Test + fun defaultCodecKeepsUnsignedMapping() { + val value = SignedAndUnsigned(5, UInt.MAX_VALUE, listOf(1), listOf(UInt.MAX_VALUE)) + val json = fory.toJson(value) + assertEquals( + "{\"signed\":\"i:5\",\"unsigned\":4294967295,\"signedList\":[\"i:1\"]," + + "\"unsignedList\":[4294967295]}", + json, + ) + assertEquals(value, fory.fromJson(json, SignedAndUnsigned::class.java)) + } + data class BinaryFields( val label: String, val bytes: ByteArray, From 9d3bf35025c63f672248a24009dd553bcb1328d8 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 21:46:01 +0100 Subject: [PATCH 05/26] style(java): keep overloads of default codec lookup together Co-Authored-By: Claude Opus 5.5 --- .../fory/json/resolver/JsonDefaultCodecs.java | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 652b682416..af18f913f0 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -174,6 +174,15 @@ public JsonCodec select(TypeRef type) { return null; } + /** + * Returns whether {@code annotation} is a default that fills a child member. The resolver keeps + * the container's own mapping when it is not the standard container representation. + */ + static boolean selectsChild(JsonCodec annotation) { + return annotation instanceof SelectedCodec + && annotation.value() == JsonCodec.NoJsonValueCodec.class; + } + /** * Returns the default for one occurrence. A primitive matches its wrapper, but a type a language * module tags with its own semantic type, such as a Kotlin {@code UInt} carried as {@code int}, @@ -186,19 +195,6 @@ private Class> codec(TypeRef type) { return codec((type.isPrimitive() ? type.wrap() : type).getType()); } - private static boolean semantic(TypeRef type) { - return type.getTypeExtMeta() != null && type.getTypeExtMeta().typeId() != Types.UNKNOWN; - } - - /** - * Returns whether {@code annotation} is a default that fills a child member. The resolver keeps - * the container's own mapping when it is not the standard container representation. - */ - static boolean selectsChild(JsonCodec annotation) { - return annotation instanceof SelectedCodec - && annotation.value() == JsonCodec.NoJsonValueCodec.class; - } - private Class> codec(Type type) { for (Entry entry : entries) { if (sameType(entry.target, type)) { @@ -208,6 +204,10 @@ private Class> codec(Type type) { return null; } + private static boolean semantic(TypeRef type) { + return type.getTypeExtMeta() != null && type.getTypeExtMeta().typeId() != Types.UNKNOWN; + } + private static Entry find(List entries, Type target) { for (Entry entry : entries) { if (sameType(entry.target, target)) { From 8a1f8d382930e5247a52e8c624eae9384b748119 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 21:55:42 +0100 Subject: [PATCH 06/26] fix(java): retain default codecs in KSP and merged models, skip unboxed carriers Co-Authored-By: Claude Opus 5.5 --- .../json/corpus/PlatformCorpusChecks.kt | 4 ++ .../kotlin/json/corpus/PlatformModels.kt | 21 ++++++++ .../json/corpus/KspRetentionResourceTest.kt | 15 ++++++ .../processing/JsonTypeProcessor.java | 1 + .../processing/JsonTypeProcessorTest.java | 49 +++++++++++++++++++ .../fory/json/meta/JsonCreatorFieldInfo.java | 6 ++- .../apache/fory/json/meta/JsonFieldInfo.java | 5 +- .../fory/json/resolver/JsonDefaultCodecs.java | 8 +++ .../fory/json/kotlin/ksp/KspModelBuilder.kt | 37 ++++++++++++++ .../json/kotlin/KotlinBuiltInCodecsTest.kt | 22 +++++++++ 10 files changed, 165 insertions(+), 3 deletions(-) diff --git a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformCorpusChecks.kt b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformCorpusChecks.kt index 1c02e1f47d..f1867aab9a 100644 --- a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformCorpusChecks.kt +++ b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformCorpusChecks.kt @@ -37,6 +37,10 @@ public object PlatformCorpusChecks { ) .values == listOf("kept") ) + val defaults = PlatformDefaultCodecs(PlatformToken("a"), listOf(PlatformToken("b"))) + val defaultsText = json.toJson(defaults) + check(defaultsText == "{\"token\":\"t:a\",\"tokens\":[\"t:b\"]}") { defaultsText } + check(json.fromJson(defaultsText, PlatformDefaultCodecs::class.java) == defaults) val type = KotlinJsonCorpus.rootType() val decoded = json.fromJson(KotlinJsonCorpus.rootJson(), type) verifyRoot(decoded) diff --git a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt index f7037dcd40..48c50c7c72 100644 --- a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt +++ b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt @@ -22,6 +22,7 @@ package org.apache.fory.integration.kotlin.json.corpus import kotlin.jvm.JvmInline import org.apache.fory.json.annotation.JsonByteArray import org.apache.fory.json.annotation.JsonCodec +import org.apache.fory.json.annotation.JsonDefaultCodec import org.apache.fory.json.annotation.JsonInclude import org.apache.fory.json.annotation.JsonMixin import org.apache.fory.json.annotation.JsonProperty @@ -94,6 +95,26 @@ public class PlatformTokenCodec : AbstractJsonValueCodec() { } } +public abstract class PlatformPrefixCodec : AbstractJsonValueCodec() + +public class PlatformDefaultTokenCodec : PlatformPrefixCodec() { + override fun write(writer: JsonWriter, value: PlatformToken?) { + if (value == null) writer.writeNull() else writer.writeString("t:" + value.value) + } + + override fun read(reader: JsonReader): PlatformToken? { + val value = reader.readString() ?: return null + return PlatformToken(value.removePrefix("t:")) + } +} + +@JsonType +@JsonDefaultCodec(PlatformDefaultTokenCodec::class) +public data class PlatformDefaultCodecs( + public val token: PlatformToken, + public val tokens: List, +) + @JsonSubTypes @JsonCodec(PlatformDirectOverrideCodec::class) public data class PlatformDirectOverride(public val value: String) diff --git a/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt b/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt index 55bc3948b0..7266055c14 100644 --- a/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt +++ b/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt @@ -101,6 +101,20 @@ public class KspRetentionResourceTest { rules("PlatformDirectOverride"), "$PACKAGE.PlatformDirectOverrideCodec", ) + val defaultCodecs = rules("PlatformDefaultCodecs") + assertConstructor(defaultCodecs, "$PACKAGE.PlatformDefaultTokenCodec") + assertTrue( + defaultCodecs.contains("-keep,allowoptimization class $PACKAGE.PlatformPrefixCodec\n"), + defaultCodecs, + ) + assertTrue( + defaultCodecs.contains("@interface org.apache.fory.json.annotation.JsonDefaultCodec\n"), + defaultCodecs, + ) + assertTrue( + defaultCodecs.contains("@interface org.apache.fory.json.annotation.JsonDefaultCodec\$List"), + defaultCodecs, + ) val mixin = mixinRules("PlatformJavaProfileMixin") assertTrue(mixin.contains("class $PACKAGE.PlatformJavaProfile"), mixin) assertTrue(mixin.contains("class $PACKAGE.PlatformJavaProfileMixin"), mixin) @@ -148,6 +162,7 @@ public class KspRetentionResourceTest { "META-INF/proguard/fory-json-$PACKAGE.PlatformAccount.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformBox.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformCircle.pro", + "META-INF/proguard/fory-json-$PACKAGE.PlatformDefaultCodecs.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformDefaults.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformNullHandling.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformDirectOverride.pro", diff --git a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java index a8ba6a52e1..d7edc9ad9b 100644 --- a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java +++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java @@ -1538,6 +1538,7 @@ void merge(Model other) { annotationTypes.addAll(other.annotationTypes); containerTypes.addAll(other.containerTypes); codecTypes.addAll(other.codecTypes); + codecSupertypes.addAll(other.codecSupertypes); binaryFallbackTypes.addAll(other.binaryFallbackTypes); annotationOwnerTypes.addAll(other.annotationOwnerTypes); nameTypes.addAll(other.nameTypes); diff --git a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java index c33a9b97bb..638e22353d 100644 --- a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java +++ b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java @@ -120,6 +120,30 @@ public void mixinPairArtifacts() throws Exception { assertTrue(rules.contains("class test." + base + "_ForyJsonCodec {"), rules); } + @Test + public void mixinDefaultCodecRules() throws Exception { + CompilationResult result = + compile( + "test.DefaultTarget", + "package test;\n" + + "import org.apache.fory.json.annotation.*;\n" + + "public final class DefaultTarget {\n" + + " public Long id;\n" + + "}\n" + + "@JsonMixin(target = DefaultTarget.class)\n" + + "@JsonDefaultCodec(DefaultMixin.LongCodec.class) interface DefaultMixin {\n" + + " abstract class Prefix extends org.apache.fory.json.codec.AbstractJsonValueCodec {}\n" + + " final class LongCodec extends Prefix {\n" + + " public void write(org.apache.fory.json.writer.JsonWriter writer, Long value) {}\n" + + " public Long read(org.apache.fory.json.reader.JsonReader reader) { return null; }\n" + + " }\n" + + "}\n"); + assertTrue(result.success, result.diagnostics()); + String rules = result.generatedResource(MIXIN_RULE_PREFIX + "test.DefaultMixin.pro"); + assertTrue(rules.contains("class test.DefaultMixin$LongCodec { public (); }"), rules); + assertTrue(rules.contains("-keep,allowoptimization class test.DefaultMixin$Prefix\n"), rules); + } + @Test public void mixinTypeCodecRules() throws Exception { CompilationResult result = @@ -2128,6 +2152,31 @@ public void subtypeRules() throws Exception { assertTrue(rules.contains("-keep,allowoptimization class external.HiddenChild"), rules); } + @Test + public void defaultCodecSupertypesMergeFromSubtypeModels() throws Exception { + assumeJava17Source(); + CompilationResult result = + compile( + "test.Priced", + "package test;\n" + + "import org.apache.fory.json.annotation.JsonDefaultCodec;\n" + + "import org.apache.fory.json.annotation.JsonSubTypes;\n" + + "@JsonSubTypes(property = \"kind\")\n" + + "public sealed interface Priced permits Priced.Item {\n" + + " abstract class Prefix extends org.apache.fory.json.codec.AbstractJsonValueCodec {}\n" + + " final class LongCodec extends Prefix {\n" + + " public void write(org.apache.fory.json.writer.JsonWriter writer, Long value) {}\n" + + " public Long read(org.apache.fory.json.reader.JsonReader reader) { return null; }\n" + + " }\n" + + " @JsonDefaultCodec(LongCodec.class)\n" + + " final class Item implements Priced { public Long price; public Item() {} }\n" + + "}\n"); + assertTrue(result.success, result.diagnostics()); + String rules = result.generatedResource(RULE_PREFIX + "test.Priced.pro"); + assertTrue(rules.contains("class test.Priced$LongCodec { public (); }"), rules); + assertTrue(rules.contains("-keep,allowoptimization class test.Priced$Prefix\n"), rules); + } + @Test public void inferredSubtypeTable() throws Exception { assumeJava17Source(); 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..1cbcedae18 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 @@ -33,6 +33,7 @@ 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.JsonDefaultCodecs; import org.apache.fory.json.resolver.JsonTypeInfo; import org.apache.fory.json.resolver.JsonTypeResolver; import org.apache.fory.reflect.TypeRef; @@ -74,11 +75,12 @@ public JsonCreatorFieldInfo( this.argumentIndex = argumentIndex; this.typeRef = typeRef; this.rawType = rawType; - this.codecAnnotation = codecAnnotation; + this.codecAnnotation = JsonDefaultCodecs.forOccurrence(codecAnnotation, unboxedRequired); this.valueCodecClass = valueCodecClass; this.formatAnnotation = formatAnnotation; this.unboxedRequired = unboxedRequired; - selectedCodec = codecAnnotation != null || valueCodecClass != null || formatAnnotation != null; + selectedCodec = + this.codecAnnotation != null || valueCodecClass != null || formatAnnotation != null; } public String name() { 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..d83a1af34c 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 @@ -51,6 +51,7 @@ 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.JsonDefaultCodecs; import org.apache.fory.json.resolver.JsonTypeInfo; import org.apache.fory.json.resolver.JsonTypeResolver; import org.apache.fory.json.writer.JsonStringEscaper; @@ -462,7 +463,9 @@ public JsonFieldInfo( && !writeRawType.isPrimitive()) { readIndexAndWriteNull |= OMIT_EMPTY_MASK; } - this.codecAnnotation = codecAnnotation; + this.codecAnnotation = + JsonDefaultCodecs.forOccurrence( + codecAnnotation, writeUnboxedRequired || readUnboxedRequired); this.valueCodecClass = valueCodecClass; this.formatAnnotation = formatAnnotation; this.writeAccessor = writeAccessor; diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index af18f913f0..5f542915e5 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -174,6 +174,14 @@ public JsonCodec select(TypeRef type) { return null; } + /** + * Returns the codec an occurrence keeps. A class default never applies to a value-class property + * that needs an unboxed carrier: it keeps its module mapping, where a declared codec would fail. + */ + public static JsonCodec forOccurrence(JsonCodec annotation, boolean unboxedRequired) { + return unboxedRequired && annotation instanceof SelectedCodec ? null : annotation; + } + /** * Returns whether {@code annotation} is a default that fills a child member. The resolver keeps * the container's own mapping when it is not the standard container representation. diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt index cc55baa3af..7b720e528b 100644 --- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt +++ b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt @@ -47,6 +47,7 @@ internal const val JSON_MIXIN: String = "org.apache.fory.json.annotation.JsonMix internal const val JSON_SUB_TYPES: String = "org.apache.fory.json.annotation.JsonSubTypes" private const val JSON_SUB_TYPE = "org.apache.fory.json.annotation.JsonSubTypes.Type" private const val JSON_CODEC = "org.apache.fory.json.annotation.JsonCodec" +private const val JSON_DEFAULT_CODEC = "org.apache.fory.json.annotation.JsonDefaultCodec" private const val JSON_BYTE_ARRAY = "org.apache.fory.json.annotation.JsonByteArray" private const val JSON_ANY_SETTER = "org.apache.fory.json.annotation.JsonAnySetter" private const val JSON_VALIDATOR = "org.apache.fory.json.annotation.JsonValidator" @@ -1147,6 +1148,14 @@ internal class KspModelBuilder( result.annotations += name when (name) { JSON_CODEC -> collectCodecAnnotation(annotation, result.codecs) + JSON_DEFAULT_CODEC -> { + // Kotlin compiles a repeated declaration into the nested container annotation. + result.annotations += "$JSON_DEFAULT_CODEC\$List" + annotation.arguments.forEach { argument -> + collectCodecType(argument.value, result.codecs) + collectCodecSupertypes(argument.value, result.types) + } + } JSON_BYTE_ARRAY -> { val format = annotation.arguments.first { it.name?.asString() == "value" }.value as KSClassDeclaration @@ -1211,6 +1220,34 @@ internal class KspModelBuilder( } } + /** + * The runtime reads a default codec's target from the generic signatures of its supertypes, so a + * shrinker must neither drop nor merge the classes on the way to `JsonValueCodec`. + */ + private fun collectCodecSupertypes(value: Any?, result: MutableSet) { + when (value) { + is KSType -> + (actual(value.declaration) as? KSClassDeclaration)?.let { collectSupertypes(it, result) } + is Iterable<*> -> value.forEach { collectCodecSupertypes(it, result) } + } + } + + private fun collectSupertypes(declaration: KSClassDeclaration, result: MutableSet) { + declaration.superTypes.forEach { reference -> + val supertype = actual(reference.resolve().declaration) as? KSClassDeclaration + val name = supertype?.let(::binaryName) + if ( + supertype != null && + name != null && + !name.startsWith("java.") && + !name.startsWith("kotlin.") && + result.add(name) + ) { + collectSupertypes(supertype, result) + } + } + } + private fun collectEndpoints( target: KSClassDeclaration, mixin: KSClassDeclaration?, diff --git a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt index e2bda96425..062ea64873 100644 --- a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt +++ b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt @@ -106,6 +106,28 @@ class KotlinBuiltInCodecsTest { val unsignedList: List, ) + @JvmInline value class Price(val amount: Long) + + class TaggedPriceCodec : AbstractJsonValueCodec() { + override fun write(writer: JsonWriter, value: Price) { + writer.writeString("p:${value.amount}") + } + + override fun read(reader: JsonReader): Price = Price(reader.readString().substring(2).toLong()) + } + + @JsonDefaultCodec(TaggedPriceCodec::class) + data class Priced(val price: Price, val prices: List) + + @Test + fun defaultCodecKeepsValueClassCarrier() { + val value = Priced(Price(10), listOf(Price(20))) + val json = fory.toJson(value) + // The unboxed property keeps the module mapping; the boxed list element uses the default. + assertEquals("{\"price\":10,\"prices\":[\"p:20\"]}", json) + assertEquals(value, fory.fromJson(json, Priced::class.java)) + } + @Test fun defaultCodecKeepsUnsignedMapping() { val value = SignedAndUnsigned(5, UInt.MAX_VALUE, listOf(1), listOf(UInt.MAX_VALUE)) From d23c24413813d9b8884fd543b9ac34e230501508 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 22:07:10 +0100 Subject: [PATCH 07/26] fix(java): retain inherited and container default codecs in KSP, reject interface and value-class misuse Co-Authored-By: Claude Opus 5.5 --- docs/json/custom-codecs.md | 4 +- .../json/corpus/PlatformCorpusChecks.kt | 6 +++ .../kotlin/json/corpus/PlatformModels.kt | 10 +++++ .../json/corpus/KspRetentionResourceTest.kt | 19 ++++++++ .../processing/ForyStructProcessor.java | 2 + .../processing/JsonTypeProcessor.java | 19 ++++++++ .../processing/JsonTypeProcessorTest.java | 20 +++++++++ .../json/annotation/JsonDefaultCodec.java | 9 ++-- .../fory/json/meta/JsonCreatorFieldInfo.java | 8 ++-- .../apache/fory/json/meta/JsonFieldInfo.java | 7 ++- .../fory/json/resolver/JsonDefaultCodecs.java | 9 ++-- .../ksp/ForyJsonKotlinSymbolProcessor.kt | 16 +++++++ .../fory/json/kotlin/ksp/KspModelBuilder.kt | 43 ++++++++++++++++++- .../json/kotlin/KotlinBuiltInCodecsTest.kt | 15 ++++--- 14 files changed, 162 insertions(+), 25 deletions(-) diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index fe4ab14691..4780c8fb0b 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -306,7 +306,9 @@ container keeps it unchanged. Properties that declare `JsonCodec`, `JsonFormat`, `JsonByteArray`, `JsonRawValue`, or `JsonUnwrapped`, and JSON Any properties, do not use defaults. Defaults declared on superclasses apply to the subclass, and a subclass default for the same target type replaces the inherited one. -A declaration on an interface is rejected. Defaults stop at the class boundary: a nested object +A declaration on an interface is rejected. A value-class property read and written through its +unboxed carrier cannot take a codec, so a default that matches one fails like a declared +`JsonCodec`; a nullable or container occurrence of the value class is boxed and uses the default. Defaults stop at the class boundary: a nested object type uses its own declarations. An exact-target Mixin may supply or replace the annotation; a Mixin that supplies or removes either the single or the repeated form replaces both forms declared on the target, and a removal also drops the defaults inherited from superclasses. diff --git a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformCorpusChecks.kt b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformCorpusChecks.kt index f1867aab9a..f0ca31a5f8 100644 --- a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformCorpusChecks.kt +++ b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformCorpusChecks.kt @@ -41,6 +41,12 @@ public object PlatformCorpusChecks { val defaultsText = json.toJson(defaults) check(defaultsText == "{\"token\":\"t:a\",\"tokens\":[\"t:b\"]}") { defaultsText } check(json.fromJson(defaultsText, PlatformDefaultCodecs::class.java) == defaults) + val inherited = PlatformInheritedDefaults(PlatformToken("c")) + check(json.toJson(inherited) == "{\"token\":\"t:c\"}") { json.toJson(inherited) } + check(json.fromJson("{\"token\":\"t:c\"}", PlatformInheritedDefaults::class.java) == inherited) + val container = PlatformContainerDefaults(PlatformToken("d")) + check(json.toJson(container) == "{\"token\":\"t:d\"}") { json.toJson(container) } + check(json.fromJson("{\"token\":\"t:d\"}", PlatformContainerDefaults::class.java) == container) val type = KotlinJsonCorpus.rootType() val decoded = json.fromJson(KotlinJsonCorpus.rootJson(), type) verifyRoot(decoded) diff --git a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt index 48c50c7c72..7e6b482381 100644 --- a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt +++ b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt @@ -115,6 +115,16 @@ public data class PlatformDefaultCodecs( public val tokens: List, ) +@JsonDefaultCodec(PlatformDefaultTokenCodec::class) +public abstract class PlatformDefaultBase + +@JsonType +public data class PlatformInheritedDefaults(public val token: PlatformToken) : PlatformDefaultBase() + +@JsonType +@JsonDefaultCodec.List(JsonDefaultCodec(PlatformDefaultTokenCodec::class)) +public data class PlatformContainerDefaults(public val token: PlatformToken) + @JsonSubTypes @JsonCodec(PlatformDirectOverrideCodec::class) public data class PlatformDirectOverride(public val value: String) diff --git a/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt b/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt index 7266055c14..dd897dbd43 100644 --- a/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt +++ b/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt @@ -115,6 +115,23 @@ public class KspRetentionResourceTest { defaultCodecs.contains("@interface org.apache.fory.json.annotation.JsonDefaultCodec\$List"), defaultCodecs, ) + for (model in listOf("PlatformInheritedDefaults", "PlatformContainerDefaults")) { + val text = rules(model) + assertConstructor(text, "$PACKAGE.PlatformDefaultTokenCodec") + assertTrue( + text.contains("-keep,allowoptimization class $PACKAGE.PlatformPrefixCodec\n"), + text, + ) + assertTrue( + text.contains("@interface org.apache.fory.json.annotation.JsonDefaultCodec\$List"), + text, + ) + assertFalse(text.contains("JsonDefaultCodec.List"), text) + } + assertTrue( + rules("PlatformInheritedDefaults").contains("class $PACKAGE.PlatformDefaultBase"), + rules("PlatformInheritedDefaults"), + ) val mixin = mixinRules("PlatformJavaProfileMixin") assertTrue(mixin.contains("class $PACKAGE.PlatformJavaProfile"), mixin) assertTrue(mixin.contains("class $PACKAGE.PlatformJavaProfileMixin"), mixin) @@ -162,11 +179,13 @@ public class KspRetentionResourceTest { "META-INF/proguard/fory-json-$PACKAGE.PlatformAccount.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformBox.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformCircle.pro", + "META-INF/proguard/fory-json-$PACKAGE.PlatformContainerDefaults.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformDefaultCodecs.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformDefaults.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformNullHandling.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformDirectOverride.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformId.pro", + "META-INF/proguard/fory-json-$PACKAGE.PlatformInheritedDefaults.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformMarker.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformOpen.pro", "META-INF/proguard/fory-json-$PACKAGE.PlatformRoot.pro", diff --git a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/ForyStructProcessor.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/ForyStructProcessor.java index ca5eda6a6f..0799f4dea7 100644 --- a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/ForyStructProcessor.java +++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/ForyStructProcessor.java @@ -114,6 +114,8 @@ private static Set supportedAnnotations() { annotations.add(JSON_MIXIN_REMOVE); annotations.add(JSON_SUB_TYPES); annotations.add(JSON_SUBTYPE_GENERATION); + annotations.add("org.apache.fory.json.annotation.JsonDefaultCodec"); + annotations.add("org.apache.fory.json.annotation.JsonDefaultCodec.List"); return Collections.unmodifiableSet(annotations); } diff --git a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java index d7edc9ad9b..4e8b4fe951 100644 --- a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java +++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java @@ -106,6 +106,7 @@ final class JsonTypeProcessor { void process(RoundEnvironment roundEnvironment) { validateMixinControls(roundEnvironment); + validateDefaultCodecOwners(roundEnvironment); collectSubtypeGenerations(roundEnvironment); TypeElement jsonType = elements.getTypeElement(JSON_TYPE); TypeElement jsonSubTypes = elements.getTypeElement(JSON_SUB_TYPES); @@ -227,6 +228,24 @@ private void validateMixinControls(RoundEnvironment roundEnvironment) { } } + /** The runtime reads JsonDefaultCodec from classes only; a Mixin source may still supply it. */ + private void validateDefaultCodecOwners(RoundEnvironment roundEnvironment) { + for (String name : new String[] {JSON_DEFAULT_CODEC, JSON_DEFAULT_CODEC_LIST}) { + TypeElement annotationType = elements.getTypeElement(name); + if (annotationType == null) { + continue; + } + for (Element element : roundEnvironment.getElementsAnnotatedWith(annotationType)) { + if (element.getKind() == ElementKind.INTERFACE && !hasAnnotation(element, JSON_MIXIN)) { + messager.printMessage( + Diagnostic.Kind.ERROR, + "@JsonDefaultCodec is read from classes only, not from interfaces", + element); + } + } + } + } + private static TypeElement enclosingType(Element element) { Element current = element; while (current != null && !(current instanceof TypeElement)) { diff --git a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java index 638e22353d..88bbac9db6 100644 --- a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java +++ b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java @@ -120,6 +120,26 @@ public void mixinPairArtifacts() throws Exception { assertTrue(rules.contains("class test." + base + "_ForyJsonCodec {"), rules); } + @Test + public void defaultCodecOnInterfaceFailsCompilation() throws Exception { + CompilationResult result = + compile( + "test.DefaultContract", + "package test;\n" + + "import org.apache.fory.json.annotation.JsonDefaultCodec;\n" + + "@JsonDefaultCodec(DefaultContract.LongCodec.class)\n" + + "public interface DefaultContract {\n" + + " final class LongCodec extends org.apache.fory.json.codec.AbstractJsonValueCodec {\n" + + " public void write(org.apache.fory.json.writer.JsonWriter writer, Long value) {}\n" + + " public Long read(org.apache.fory.json.reader.JsonReader reader) { return null; }\n" + + " }\n" + + "}\n"); + assertFalse(result.success); + assertTrue( + result.diagnostics().contains("@JsonDefaultCodec is read from classes only"), + result.diagnostics()); + } + @Test public void mixinDefaultCodecRules() throws Exception { CompilationResult result = diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java index 4e9885a5e6..aa67aa9955 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java @@ -50,9 +50,12 @@ * {@link JsonRawValue}, or {@link JsonUnwrapped}, and JSON Any properties, do not use defaults. * Defaults declared on superclasses apply too, and a subclass default for the same target type * replaces the inherited one. Declarations on interfaces are rejected. Defaults do not reach nested - * object types, which use their own class declarations. An exact-target {@link JsonMixin} may - * supply or replace this annotation; supplying or removing either the single or the repeated form - * replaces both forms declared on the target, and a removal also drops inherited defaults. + * object types, which use their own class declarations. A value-class property read and written + * through its unboxed carrier cannot take a codec, so a default that matches one fails like a + * declared {@link JsonCodec}; a nullable or container occurrence of the value class is boxed and + * uses the default. An exact-target {@link JsonMixin} may supply or replace this annotation; + * supplying or removing either the single or the repeated form replaces both forms declared on the + * target, and a removal also drops inherited defaults. */ @Documented @Retention(RetentionPolicy.RUNTIME) 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 1cbcedae18..5fbe7230bd 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 @@ -75,12 +75,11 @@ public JsonCreatorFieldInfo( this.argumentIndex = argumentIndex; this.typeRef = typeRef; this.rawType = rawType; - this.codecAnnotation = JsonDefaultCodecs.forOccurrence(codecAnnotation, unboxedRequired); + this.codecAnnotation = codecAnnotation; this.valueCodecClass = valueCodecClass; this.formatAnnotation = formatAnnotation; this.unboxedRequired = unboxedRequired; - selectedCodec = - this.codecAnnotation != null || valueCodecClass != null || formatAnnotation != null; + selectedCodec = codecAnnotation != null || valueCodecClass != null || formatAnnotation != null; } public String name() { @@ -159,7 +158,8 @@ public void resolveType(JsonTypeResolver resolver) { "JSON creator property " + name + " cannot select a codec or format for the unboxed logical type " - + typeRef); + + typeRef + + JsonDefaultCodecs.origin(codecAnnotation)); } JsonTypeInfo canonical = resolver.withContentNullRead(resolver.getTypeInfo(typeRef), onContentNullRead); 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 d83a1af34c..43b2257d02 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 @@ -463,9 +463,7 @@ public JsonFieldInfo( && !writeRawType.isPrimitive()) { readIndexAndWriteNull |= OMIT_EMPTY_MASK; } - this.codecAnnotation = - JsonDefaultCodecs.forOccurrence( - codecAnnotation, writeUnboxedRequired || readUnboxedRequired); + this.codecAnnotation = codecAnnotation; this.valueCodecClass = valueCodecClass; this.formatAnnotation = formatAnnotation; this.writeAccessor = writeAccessor; @@ -923,7 +921,8 @@ public void resolveTypes(JsonTypeResolver typeResolver) { "JSON property " + name + " cannot select a codec or format for the unboxed logical type " - + codecType); + + codecType + + JsonDefaultCodecs.origin(codecAnnotation)); } JsonTypeInfo selectedTypeInfo = codecAnnotation != null diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 5f542915e5..0c9232bbc1 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -174,12 +174,9 @@ public JsonCodec select(TypeRef type) { return null; } - /** - * Returns the codec an occurrence keeps. A class default never applies to a value-class property - * that needs an unboxed carrier: it keeps its module mapping, where a declared codec would fail. - */ - public static JsonCodec forOccurrence(JsonCodec annotation, boolean unboxedRequired) { - return unboxedRequired && annotation instanceof SelectedCodec ? null : annotation; + /** Names a class default as the source of {@code annotation} in an error, or returns "". */ + public static String origin(JsonCodec annotation) { + return annotation instanceof SelectedCodec ? " selected by the class @JsonDefaultCodec" : ""; } /** diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt index dbcfc015ea..6e102be7d9 100644 --- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt +++ b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt @@ -25,6 +25,7 @@ import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.processing.SymbolProcessorEnvironment +import com.google.devtools.ksp.symbol.ClassKind import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.validate @@ -58,6 +59,19 @@ internal class ForyJsonKotlinSymbolProcessor(environment: SymbolProcessorEnviron if (!generatedRequests.add(R8RulesWriter.resourcePath(model))) continue write(model) } + // The runtime reads JsonDefaultCodec from classes only; a Mixin source may still supply it. + sequenceOf(JSON_DEFAULT_CODEC_NAME, "$JSON_DEFAULT_CODEC_NAME.List") + .flatMap(resolver::getSymbolsWithAnnotation) + .filterIsInstance() + .filter { it.classKind == ClassKind.INTERFACE } + .filter { declaration -> + declaration.annotations.none { + it.annotationType.resolve().declaration.qualifiedName?.asString() == JSON_MIXIN + } + } + .forEach { + logger.error("@JsonDefaultCodec is read from classes only, not from interfaces", it) + } for (symbol in resolver.getSymbolsWithAnnotation(JSON_MIXIN)) { if (!symbol.validate()) { deferred += symbol @@ -102,3 +116,5 @@ internal class ForyJsonKotlinSymbolProcessor(environment: SymbolProcessorEnviron } } } + +private const val JSON_DEFAULT_CODEC_NAME = "org.apache.fory.json.annotation.JsonDefaultCodec" diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt index 7b720e528b..152eec1de9 100644 --- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt +++ b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt @@ -48,6 +48,7 @@ internal const val JSON_SUB_TYPES: String = "org.apache.fory.json.annotation.Jso private const val JSON_SUB_TYPE = "org.apache.fory.json.annotation.JsonSubTypes.Type" private const val JSON_CODEC = "org.apache.fory.json.annotation.JsonCodec" private const val JSON_DEFAULT_CODEC = "org.apache.fory.json.annotation.JsonDefaultCodec" +private const val JSON_DEFAULT_CODEC_LIST = "$JSON_DEFAULT_CODEC.List" private const val JSON_BYTE_ARRAY = "org.apache.fory.json.annotation.JsonByteArray" private const val JSON_ANY_SETTER = "org.apache.fory.json.annotation.JsonAnySetter" private const val JSON_VALIDATOR = "org.apache.fory.json.annotation.JsonValidator" @@ -1084,10 +1085,43 @@ internal class KspModelBuilder( .forEach(result.annotations::add) } } + collectInheritedDefaultCodecs(target, mixin, result) collectEndpoints(target, mixin, result) return result } + /** + * The runtime reads `JsonDefaultCodec` from every superclass, so declarations inherited from a + * class that is not itself a JSON model need the same retention. A Mixin removal on the target + * drops inherited defaults, as it does at runtime; interfaces are rejected there. + */ + private fun collectInheritedDefaultCodecs( + target: KSClassDeclaration, + mixin: KSClassDeclaration?, + result: Retention, + ) { + if ( + mixin != null && + (removesAnnotation(mixin, JSON_DEFAULT_CODEC) || + removesAnnotation(mixin, JSON_DEFAULT_CODEC_LIST)) + ) { + return + } + target.getAllSuperTypes().forEach { supertype -> + val owner = actual(supertype.declaration) as? KSClassDeclaration ?: return@forEach + if (owner.classKind != ClassKind.CLASS) return@forEach + owner.annotations + .filter { + val name = annotationName(it) + name == JSON_DEFAULT_CODEC || name == JSON_DEFAULT_CODEC_LIST + } + .forEach { annotation -> + collectAnnotation(annotation, result) + binaryName(owner)?.let(result.annotationOwners::add) + } + } + } + private fun effectiveAnnotations( target: KSAnnotated, mixin: KSClassDeclaration?, @@ -1145,7 +1179,8 @@ internal class KspModelBuilder( private fun collectAnnotation(annotation: KSAnnotation, result: Retention) { val name = annotationName(annotation) if (!name.startsWith(JSON_ANNOTATION_PACKAGE) || name in CONTROL_ANNOTATIONS) return - result.annotations += name + // Keep rules name the nested container by its JVM binary name. + result.annotations += if (name == JSON_DEFAULT_CODEC_LIST) "$JSON_DEFAULT_CODEC\$List" else name when (name) { JSON_CODEC -> collectCodecAnnotation(annotation, result.codecs) JSON_DEFAULT_CODEC -> { @@ -1156,6 +1191,12 @@ internal class KspModelBuilder( collectCodecSupertypes(argument.value, result.types) } } + JSON_DEFAULT_CODEC_LIST -> + annotation.arguments.forEach { argument -> + (argument.value as? Iterable<*>)?.filterIsInstance()?.forEach { + collectAnnotation(it, result) + } + } JSON_BYTE_ARRAY -> { val format = annotation.arguments.first { it.name?.asString() == "value" }.value as KSClassDeclaration diff --git a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt index 062ea64873..6c3c646088 100644 --- a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt +++ b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt @@ -116,16 +116,19 @@ class KotlinBuiltInCodecsTest { override fun read(reader: JsonReader): Price = Price(reader.readString().substring(2).toLong()) } + @JsonDefaultCodec(TaggedPriceCodec::class) data class Priced(val price: Price) + @JsonDefaultCodec(TaggedPriceCodec::class) - data class Priced(val price: Price, val prices: List) + data class BoxedPrices(val price: Price?, val prices: List) @Test - fun defaultCodecKeepsValueClassCarrier() { - val value = Priced(Price(10), listOf(Price(20))) + fun defaultCodecOnValueClassCarrierFails() { + val error = assertFailsWith { fory.toJson(Priced(Price(10))) } + assertTrue(error.message.orEmpty().contains("@JsonDefaultCodec"), error.message) + val value = BoxedPrices(Price(10), listOf(Price(20))) val json = fory.toJson(value) - // The unboxed property keeps the module mapping; the boxed list element uses the default. - assertEquals("{\"price\":10,\"prices\":[\"p:20\"]}", json) - assertEquals(value, fory.fromJson(json, Priced::class.java)) + assertEquals("{\"price\":\"p:10\",\"prices\":[\"p:20\"]}", json) + assertEquals(value, fory.fromJson(json, BoxedPrices::class.java)) } @Test From 468793ccf2297a77759a29ac7d047acd69061878 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 22:11:57 +0100 Subject: [PATCH 08/26] fix(kotlin): keep repeated default codecs supplied by a KSP Mixin Co-Authored-By: Claude Opus 5.5 --- .../kotlin/json/corpus/PlatformModels.kt | 29 +++++++++++++++++-- .../json/corpus/KotlinJsonCorpusTest.kt | 16 ++++++++++ .../json/corpus/KspRetentionResourceTest.kt | 8 +++++ .../fory/json/kotlin/ksp/KspModelBuilder.kt | 19 ++++++++++-- 4 files changed, 66 insertions(+), 6 deletions(-) diff --git a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt index 7e6b482381..2a3359592d 100644 --- a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt +++ b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt @@ -115,16 +115,39 @@ public data class PlatformDefaultCodecs( public val tokens: List, ) -@JsonDefaultCodec(PlatformDefaultTokenCodec::class) -public abstract class PlatformDefaultBase +@JsonDefaultCodec(PlatformDefaultTokenCodec::class) public abstract class PlatformDefaultBase @JsonType -public data class PlatformInheritedDefaults(public val token: PlatformToken) : PlatformDefaultBase() +public data class PlatformInheritedDefaults(public val token: PlatformToken) : + PlatformDefaultBase() @JsonType @JsonDefaultCodec.List(JsonDefaultCodec(PlatformDefaultTokenCodec::class)) public data class PlatformContainerDefaults(public val token: PlatformToken) +public data class PlatformLabel(public val value: String) + +public class PlatformLabelCodec : PlatformPrefixCodec() { + override fun write(writer: JsonWriter, value: PlatformLabel?) { + if (value == null) writer.writeNull() else writer.writeString("l:" + value.value) + } + + override fun read(reader: JsonReader): PlatformLabel? { + val value = reader.readString() ?: return null + return PlatformLabel(value.removePrefix("l:")) + } +} + +public data class PlatformMixinDefaultsTarget( + public val token: PlatformToken, + public val label: PlatformLabel, +) + +@JsonMixin(target = PlatformMixinDefaultsTarget::class) +@JsonDefaultCodec(PlatformDefaultTokenCodec::class) +@JsonDefaultCodec(PlatformLabelCodec::class) +public interface PlatformMixinDefaults + @JsonSubTypes @JsonCodec(PlatformDirectOverrideCodec::class) public data class PlatformDirectOverride(public val value: String) diff --git a/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KotlinJsonCorpusTest.kt b/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KotlinJsonCorpusTest.kt index 7b80d3efa7..fcb5a4d9ab 100644 --- a/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KotlinJsonCorpusTest.kt +++ b/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KotlinJsonCorpusTest.kt @@ -47,6 +47,22 @@ public class KotlinJsonCorpusTest { } } + @Test + public fun mixinRepeatedDefaults(): Unit { + for (codegen in listOf(false, true)) { + val json = + ForyJsonKotlin.builder() + .withCodegen(codegen) + .withAsyncCompilation(false) + .registerMixin(PlatformMixinDefaults::class.java) + .build() + val value = PlatformMixinDefaultsTarget(PlatformToken("a"), PlatformLabel("b")) + val text = json.toJson(value) + assertEquals(text, "{\"token\":\"t:a\",\"label\":\"l:b\"}") + assertEquals(json.fromJson(text, PlatformMixinDefaultsTarget::class.java), value) + } + } + @Test public fun sharedRoundTrip(): Unit { val json = diff --git a/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt b/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt index dd897dbd43..3273d54663 100644 --- a/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt +++ b/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt @@ -132,6 +132,13 @@ public class KspRetentionResourceTest { rules("PlatformInheritedDefaults").contains("class $PACKAGE.PlatformDefaultBase"), rules("PlatformInheritedDefaults"), ) + val mixinDefaults = mixinRules("PlatformMixinDefaults") + assertConstructor(mixinDefaults, "$PACKAGE.PlatformDefaultTokenCodec") + assertConstructor(mixinDefaults, "$PACKAGE.PlatformLabelCodec") + assertTrue( + mixinDefaults.contains("-keep,allowoptimization class $PACKAGE.PlatformPrefixCodec\n"), + mixinDefaults, + ) val mixin = mixinRules("PlatformJavaProfileMixin") assertTrue(mixin.contains("class $PACKAGE.PlatformJavaProfile"), mixin) assertTrue(mixin.contains("class $PACKAGE.PlatformJavaProfileMixin"), mixin) @@ -193,6 +200,7 @@ public class KspRetentionResourceTest { "META-INF/proguard/fory-json-$PACKAGE.PlatformSquare.pro", "META-INF/proguard/fory-json-mixin-$PACKAGE.PlatformJavaProfileMixin.pro", "META-INF/proguard/fory-json-mixin-$PACKAGE.PlatformDefaultMixin.pro", + "META-INF/proguard/fory-json-mixin-$PACKAGE.PlatformMixinDefaults.pro", "META-INF/proguard/fory-json-mixin-$PACKAGE.PlatformMixinOverrideAnnotations.pro", ) } diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt index 152eec1de9..bd7eccec38 100644 --- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt +++ b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt @@ -1127,22 +1127,35 @@ internal class KspModelBuilder( mixin: KSClassDeclaration?, ): Sequence = sequence { val source = mixin?.let { matchingMixinSource(target, it) } + // A repeatable annotation may appear several times, so replacements are grouped, not keyed. val replacements = source ?.annotations ?.filter { annotationName(it) !in CONTROL_ANNOTATIONS } - ?.associateBy(::annotationName) + ?.groupBy { replacementKey(annotationName(it)) } .orEmpty() for (annotation in target.annotations) { val name = annotationName(annotation) if (!name.startsWith(JSON_ANNOTATION_PACKAGE)) continue - if (name !in replacements && (source == null || !removesAnnotation(source, name))) { + if (replacementKey(name) !in replacements && (source == null || !removes(source, name))) { yield(annotation) } } - replacements.values.forEach { yield(it) } + replacements.values.forEach { group -> group.forEach { yield(it) } } } + /** The single and the container form of JsonDefaultCodec replace each other, as at runtime. */ + private fun replacementKey(name: String): String = + if (name == JSON_DEFAULT_CODEC_LIST) JSON_DEFAULT_CODEC else name + + private fun removes(source: KSAnnotated, name: String): Boolean = + if (replacementKey(name) == JSON_DEFAULT_CODEC) { + removesAnnotation(source, JSON_DEFAULT_CODEC) || + removesAnnotation(source, JSON_DEFAULT_CODEC_LIST) + } else { + removesAnnotation(source, name) + } + private fun matchingMixinSource( target: KSAnnotated, mixin: KSClassDeclaration, From db4463b6819199d0e5f9707fec874374d5989ac3 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 22:15:38 +0100 Subject: [PATCH 09/26] fix(java): reject Kotlin unsigned default targets, document and test null ownership Co-Authored-By: Claude Opus 5.5 --- docs/json/custom-codecs.md | 4 +- .../json/annotation/JsonDefaultCodec.java | 11 ++-- .../fory/json/resolver/JsonDefaultCodecs.java | 14 ++++ .../fory/json/JsonDefaultCodecTest.java | 65 +++++++++++++++++++ .../json/kotlin/KotlinBuiltInCodecsTest.kt | 16 +++++ 5 files changed, 104 insertions(+), 6 deletions(-) diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index 4780c8fb0b..1b5f06c621 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -306,7 +306,9 @@ container keeps it unchanged. Properties that declare `JsonCodec`, `JsonFormat`, `JsonByteArray`, `JsonRawValue`, or `JsonUnwrapped`, and JSON Any properties, do not use defaults. Defaults declared on superclasses apply to the subclass, and a subclass default for the same target type replaces the inherited one. -A declaration on an interface is rejected. A value-class property read and written through its +A default codec is used exactly like a property `JsonCodec`, so it receives and owns null as +described above for every property it reaches. A declaration on an interface is rejected, and so +is a target that is a Kotlin unsigned type, which the Kotlin module carries as a tagged primitive. A value-class property read and written through its unboxed carrier cannot take a codec, so a default that matches one fails like a declared `JsonCodec`; a nullable or container occurrence of the value class is boxed and uses the default. Defaults stop at the class boundary: a nested object type uses its own declarations. An exact-target Mixin may supply or replace the annotation; a Mixin diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java index aa67aa9955..d26948bbea 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java @@ -49,11 +49,12 @@ *

A property that declares its own {@link JsonCodec}, {@link JsonFormat}, {@link JsonByteArray}, * {@link JsonRawValue}, or {@link JsonUnwrapped}, and JSON Any properties, do not use defaults. * Defaults declared on superclasses apply too, and a subclass default for the same target type - * replaces the inherited one. Declarations on interfaces are rejected. Defaults do not reach nested - * object types, which use their own class declarations. A value-class property read and written - * through its unboxed carrier cannot take a codec, so a default that matches one fails like a - * declared {@link JsonCodec}; a nullable or container occurrence of the value class is boxed and - * uses the default. An exact-target {@link JsonMixin} may supply or replace this annotation; + * replaces the inherited one. A default codec receives and owns null like a property {@link + * JsonCodec}. Declarations on interfaces and Kotlin unsigned targets are rejected. Defaults do not + * reach nested object types, which use their own class declarations. A value-class property read + * and written through its unboxed carrier cannot take a codec, so a default that matches one fails + * like a declared {@link JsonCodec}; a nullable or container occurrence of the value class is boxed + * and uses the default. An exact-target {@link JsonMixin} may supply or replace this annotation; * supplying or removing either the single or the repeated form replaces both forms declared on the * target, and a removal also drops inherited defaults. */ diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 0c9232bbc1..294807ed41 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -51,6 +51,16 @@ @Internal public final class JsonDefaultCodecs { private static final JsonDefaultCodecs NONE = new JsonDefaultCodecs(new Entry[0]); + private static final List KOTLIN_UNSIGNED = + Arrays.asList( + "kotlin.UByte", + "kotlin.UShort", + "kotlin.UInt", + "kotlin.ULong", + "kotlin.UByteArray", + "kotlin.UShortArray", + "kotlin.UIntArray", + "kotlin.ULongArray"); private final Entry[] entries; @@ -234,6 +244,10 @@ private static Type targetType( if (target == null || !concrete(target)) { throw invalid(declaring, codecClass, "does not declare a concrete value type"); } + if (target instanceof Class && KOTLIN_UNSIGNED.contains(((Class) target).getName())) { + // The Kotlin module carries these as tagged JVM primitives, so no occurrence could match. + throw invalid(declaring, codecClass, "cannot target the Kotlin unsigned type " + target); + } return target; } diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index d1760a5790..43a5cc7e31 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -752,6 +752,68 @@ public void representationAnnotationsAndAnyValuesKeepTheirMapping() { assertTrue(!text.contains("d:") && !text.contains("s:") && !text.contains("b:"), text); } + /** A default reaches properties the author never annotated, so it must own null itself. */ + public static final class NullableTaggedCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, BigDecimal value) { + if (value == null) { + writer.writeNull(); + } else { + writer.writeString("n:" + value.toPlainString()); + } + } + + @Override + public BigDecimal read(JsonReader reader) { + return reader.tryReadNull() ? null : new BigDecimal(reader.readString().substring(2)); + } + } + + @JsonDefaultCodec(NullableTaggedCodec.class) + public static class NullablePrices { + @JsonProperty(include = JsonProperty.Include.ALWAYS) + public BigDecimal price; + + public List floors; + public Map byKey; + } + + @Test + public void defaultCodecOwnsNullWithDefaultSettings() { + ForyJson json = newJson(); + NullablePrices value = new NullablePrices(); + value.floors = Arrays.asList(TEN, null); + value.byKey = Collections.singletonMap("k", null); + String text = json.toJson(value); + assertEquals(text, "{\"price\":null,\"floors\":[\"n:10\",null],\"byKey\":{\"k\":null}}"); + NullablePrices read = json.fromJson(text, NullablePrices.class); + assertEquals(read.price, null); + assertEquals(read.floors, Arrays.asList(PLAIN_TEN, null)); + assertEquals(read.byKey, Collections.singletonMap("k", null)); + } + + public interface Contract {} + + @JsonDefaultCodec(TaggedDecimalCodec.class) + public interface AnnotatedContract {} + + public interface ExtendsAnnotated extends AnnotatedContract {} + + public static class ImplementsThroughSuperinterface implements ExtendsAnnotated { + public BigDecimal price; + } + + public static class AnnotatedBase implements AnnotatedContract {} + + public static class ImplementsThroughSuperclass extends AnnotatedBase implements Contract { + public BigDecimal price; + } + + @JsonDefaultCodec(JsonCodec.NoJsonValueCodec.class) + public static class SentinelTarget { + public BigDecimal price; + } + @JsonDefaultCodec({TaggedDecimalCodec.class, OtherDecimalCodec.class}) public static class DuplicateTarget { public BigDecimal price; @@ -775,6 +837,9 @@ public void invalidDeclarations() { assertInvalid(json, RepeatedDuplicateTarget.class, "Duplicate @JsonDefaultCodec target"); assertInvalid(json, NoConcreteTarget.class, "does not declare a concrete value type"); assertInvalid(json, ImplementsDefaults.class, "not from interface"); + assertInvalid(json, ImplementsThroughSuperinterface.class, "not from interface"); + assertInvalid(json, ImplementsThroughSuperclass.class, "not from interface"); + assertInvalid(json, SentinelTarget.class, "is not a codec"); } private static void assertInvalid(ForyJson json, Class type, String message) { diff --git a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt index 6c3c646088..cc02ddbc12 100644 --- a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt +++ b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt @@ -131,6 +131,22 @@ class KotlinBuiltInCodecsTest { assertEquals(value, fory.fromJson(json, BoxedPrices::class.java)) } + class UIntTagCodec : AbstractJsonValueCodec() { + override fun write(writer: JsonWriter, value: UInt) { + writer.writeString("u:$value") + } + + override fun read(reader: JsonReader): UInt = reader.readString().substring(2).toUInt() + } + + @JsonDefaultCodec(UIntTagCodec::class) data class UnsignedTarget(val value: UInt) + + @Test + fun defaultCodecRejectsUnsignedTarget() { + val error = assertFailsWith { fory.toJson(UnsignedTarget(1u)) } + assertTrue(error.message.orEmpty().contains("Kotlin unsigned type"), error.message) + } + @Test fun defaultCodecKeepsUnsignedMapping() { val value = SignedAndUnsigned(5, UInt.MAX_VALUE, listOf(1), listOf(UInt.MAX_VALUE)) From 36c4f60dc689912cb0cbd88a7985f35688585e5b Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 22:23:38 +0100 Subject: [PATCH 10/26] fix(java): check container ownership inside the resolution snapshot, pin wildcard children Co-Authored-By: Claude Opus 5.5 --- docs/json/custom-codecs.md | 3 +- .../json/resolver/JsonSharedRegistry.java | 3 +- .../fory/json/resolver/JsonTypeResolver.java | 15 +++--- .../fory/json/JsonDefaultCodecTest.java | 49 +++++++++++++++++++ 4 files changed, 61 insertions(+), 9 deletions(-) diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index 1b5f06c621..4990723595 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -299,7 +299,8 @@ declared `@JsonCodec(value = ...)`; a primitive property or array element matche Otherwise a target equal to the direct child of an array, `Collection`, `AtomicReferenceArray`, `Optional`, `AtomicReference`, or the value of a `Map` fills the matching child member from the table above, so a `Byte` default writes a `byte[]` as a JSON array of codec values whatever -`byteArrayFormat` says. Deeper nesting is not searched. A child is filled only where the container keeps its +`byteArrayFormat` says. Deeper nesting is not searched, and a wildcard child such as `List` keeps its +mapping, as an explicit child member would reject it. A child is filled only where the container keeps its standard mapping: a registered codec or factory, a module, or a type declaration that owns the container keeps it unchanged. 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 e4c28f6bb6..854a5d7342 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 @@ -1272,7 +1272,8 @@ public A annotation( /** * Returns whether a representation other than the standard container mapping owns this container - * type. It follows {@link #resolveCodec} without resolving the container's children. + * type, in {@link #resolveCodec} order. Only an installed module factory is asked by building its + * codec, which may resolve children; the standard mapping itself is never built here. */ boolean ownsContainer(TypeRef typeRef, JsonTypeResolver localResolver) { Class rawType = typeRef.getRawType(); 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 5b1b1df9b8..4b11e5def4 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 @@ -419,15 +419,16 @@ public JsonTypeInfo getTypeInfo(TypeRef declaredType, JsonCodec annotation) { if (annotation == null) { return getTypeInfo(declaredType); } - // A class default fills a child only where the container keeps its standard mapping, so a - // registration, factory, module, or type declaration that owns the container still wins. - if (JsonDefaultCodecs.selectsChild(annotation) - && sharedRegistry.ownsContainer(declaredType, this)) { - return getTypeInfo(declaredType); - } ResolutionSnapshot snapshot = beginResolution(); try { - JsonTypeInfo result = resolveTypeInfo(declaredType, annotation); + // A class default fills a child only where the container keeps its standard mapping, so a + // registration, factory, module, or type declaration that owns the container still wins. + // The check runs inside the snapshot because a module factory may resolve child types. + JsonTypeInfo result = + JsonDefaultCodecs.selectsChild(annotation) + && sharedRegistry.ownsContainer(declaredType, this) + ? getTypeInfo(declaredType) + : resolveTypeInfo(declaredType, annotation); completeResolution(snapshot); return result; } catch (RuntimeException | Error e) { diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index 43a5cc7e31..f576c238c3 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -814,6 +814,55 @@ public static class SentinelTarget { public BigDecimal price; } + @JsonDefaultCodec(TaggedDecimalCodec.class) + public static class WildcardPrices { + public List prices; + } + + @Test + public void wildcardChildrenKeepTheirMapping() { + WildcardPrices value = new WildcardPrices(); + value.prices = Collections.singletonList(TEN); + // A wildcard is not a concrete child, which an explicit elementCodec rejects as well. + assertEquals(newJson().toJson(value), "{\"prices\":[1E+1]}"); + } + + @JsonDefaultCodec(TaggedDecimalCodec.class) + public static class TreeNode { + public BigDecimal value; + public List children; + } + + @Test + public void moduleFactoryResolvingSelfReferencingChildren() { + JsonCodecFactory factory = + (type, resolver, runtimeType) -> { + if (type.getRawType() != List.class) { + return null; + } + // Resolving the element re-enters the type that is still being built. + resolver.getTypeInfo(org.apache.fory.json.codec.CodecUtils.elementTypeRef(type)); + return new AbstractJsonValueCodec>() { + @Override + public void write(JsonWriter writer, List value) { + writer.writeString("list:" + value.size()); + } + + @Override + public List read(JsonReader reader) { + reader.readString(); + return Collections.emptyList(); + } + }; + }; + ForyJson json = + newJsonBuilder().withModule(context -> context.registerCodecFactory(factory)).build(); + TreeNode node = new TreeNode(); + node.value = TEN; + node.children = Collections.singletonList(new TreeNode()); + assertEquals(json.toJson(node), "{\"value\":\"d:10\",\"children\":\"list:1\"}"); + } + @JsonDefaultCodec({TaggedDecimalCodec.class, OtherDecimalCodec.class}) public static class DuplicateTarget { public BigDecimal price; From 93b5db39b8ba3e1a0dd8150ca67f06e69c5c0960 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 22:31:32 +0100 Subject: [PATCH 11/26] fix(java): match Kotlin covariant and generic-array targets, reject enum declarations Co-Authored-By: Claude Opus 5.5 --- docs/json/custom-codecs.md | 36 +++++++----- .../processing/JsonTypeProcessor.java | 10 +++- .../processing/JsonTypeProcessorTest.java | 22 ++++++++ .../json/annotation/JsonDefaultCodec.java | 3 +- .../fory/json/resolver/JsonDefaultCodecs.java | 55 ++++++++++++++++--- .../fory/json/JsonDefaultCodecTest.java | 16 +++++- .../ksp/ForyJsonKotlinSymbolProcessor.kt | 8 ++- .../json/kotlin/KotlinBuiltInCodecsTest.kt | 40 ++++++++++++++ 8 files changed, 160 insertions(+), 30 deletions(-) diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index 4990723595..f078b2d53d 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -296,25 +296,31 @@ one class may name at most one codec per target type. A property or creator parameter whose resolved type equals a target uses the codec as if it declared `@JsonCodec(value = ...)`; a primitive property or array element matches its wrapper type. +A target written as `? extends T`, which Kotlin emits for declaration-site variance, reads as `T`. + Otherwise a target equal to the direct child of an array, `Collection`, `AtomicReferenceArray`, `Optional`, `AtomicReference`, or the value of a `Map` fills the matching child member from the table above, so a `Byte` default writes a `byte[]` as a JSON array of codec values whatever -`byteArrayFormat` says. Deeper nesting is not searched, and a wildcard child such as `List` keeps its -mapping, as an explicit child member would reject it. A child is filled only where the container keeps its -standard mapping: a registered codec or factory, a module, or a type declaration that owns the -container keeps it unchanged. - -Properties that declare `JsonCodec`, `JsonFormat`, `JsonByteArray`, `JsonRawValue`, or -`JsonUnwrapped`, and JSON Any properties, do not use defaults. Defaults declared on superclasses -apply to the subclass, and a subclass default for the same target type replaces the inherited one. +`byteArrayFormat` says. A child is filled only where the container keeps its standard mapping: a +registered codec or factory, a module, or a type declaration that owns the container keeps it +unchanged. Deeper nesting is not searched, and a wildcard child such as `List` +keeps its mapping, as an explicit child member would reject it. + A default codec is used exactly like a property `JsonCodec`, so it receives and owns null as -described above for every property it reaches. A declaration on an interface is rejected, and so -is a target that is a Kotlin unsigned type, which the Kotlin module carries as a tagged primitive. A value-class property read and written through its -unboxed carrier cannot take a codec, so a default that matches one fails like a declared -`JsonCodec`; a nullable or container occurrence of the value class is boxed and uses the default. Defaults stop at the class boundary: a nested object -type uses its own declarations. An exact-target Mixin may supply or replace the annotation; a Mixin -that supplies or removes either the single or the repeated form replaces both forms declared on the -target, and a removal also drops the defaults inherited from superclasses. +described above for every property it reaches. Properties that declare `JsonCodec`, `JsonFormat`, +`JsonByteArray`, `JsonRawValue`, or `JsonUnwrapped`, and JSON Any properties, do not use defaults. +A value-class property read and written through its unboxed carrier cannot take a codec, so a +default that matches one fails like a declared `JsonCodec`; a nullable or container occurrence of +the value class is boxed and uses the default. A target that is a Kotlin unsigned type, which the +Kotlin module carries as a tagged primitive, is rejected. + +Defaults declared on superclasses apply to the subclass, and a subclass default for the same target +type replaces the inherited one. Defaults stop at the class boundary: a nested object type uses its +own declarations. A declaration on an interface is rejected; the build-time processors also reject +one on an enum or annotation type, which never gets an object mapping. An exact-target Mixin may +supply or replace the annotation; a Mixin that supplies or removes either the single or the +repeated form replaces both forms declared on the target, and a removal also drops the defaults +inherited from superclasses. ### Kotlin occurrences diff --git a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java index 4e8b4fe951..70addccdef 100644 --- a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java +++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java @@ -236,10 +236,16 @@ private void validateDefaultCodecOwners(RoundEnvironment roundEnvironment) { continue; } for (Element element : roundEnvironment.getElementsAnnotatedWith(annotationType)) { - if (element.getKind() == ElementKind.INTERFACE && !hasAnnotation(element, JSON_MIXIN)) { + ElementKind kind = element.getKind(); + boolean notClass = + kind == ElementKind.INTERFACE + || kind == ElementKind.ENUM + || kind == ElementKind.ANNOTATION_TYPE; + if (notClass && !hasAnnotation(element, JSON_MIXIN)) { messager.printMessage( Diagnostic.Kind.ERROR, - "@JsonDefaultCodec is read from classes only, not from interfaces", + "@JsonDefaultCodec is read from classes only, not from interfaces, enums, or" + + " annotation types", element); } } diff --git a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java index 88bbac9db6..739c3c9c59 100644 --- a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java +++ b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java @@ -140,6 +140,28 @@ public void defaultCodecOnInterfaceFailsCompilation() throws Exception { result.diagnostics()); } + @Test + public void defaultCodecOnEnumFailsCompilation() throws Exception { + CompilationResult result = + compile( + "test.DefaultStatus", + "package test;\n" + + "import org.apache.fory.json.annotation.JsonDefaultCodec;\n" + + "@JsonDefaultCodec(DefaultStatus.LongCodec.class)\n" + + "public enum DefaultStatus {\n" + + " ACTIVE;\n" + + " public static final class LongCodec\n" + + " extends org.apache.fory.json.codec.AbstractJsonValueCodec {\n" + + " public void write(org.apache.fory.json.writer.JsonWriter writer, Long value) {}\n" + + " public Long read(org.apache.fory.json.reader.JsonReader reader) { return null; }\n" + + " }\n" + + "}\n"); + assertFalse(result.success); + assertTrue( + result.diagnostics().contains("@JsonDefaultCodec is read from classes only"), + result.diagnostics()); + } + @Test public void mixinDefaultCodecRules() throws Exception { CompilationResult result = diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java index d26948bbea..9560953fc8 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java @@ -36,7 +36,8 @@ *

Each codec targets the type argument it declares for {@link JsonValueCodec}: a codec of {@code * BigDecimal} targets {@code BigDecimal}, a codec of {@code Optional} targets exactly * {@code Optional}. That type must be concrete, without type variables or wildcards, - * and one class may name at most one codec per target type. + * except that a covariant {@code ? extends T}, which Kotlin emits, reads as {@code T}. One class + * may name at most one codec per target type. * *

A property or creator parameter whose resolved type equals a target uses that codec as if it * declared {@code @JsonCodec(value = ...)}; a primitive property or array element matches its diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 294807ed41..027ce90ca2 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -23,6 +23,7 @@ import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; +import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -163,22 +164,22 @@ public JsonCodec select(TypeRef type) { } Class rawType = type.getRawType(); if (rawType.isArray()) { - codec = codec(type.getComponentType()); + codec = childCodec(type.getComponentType()); return codec == null ? null : new SelectedCodec(null, codec, null, null); } if (rawType.getTypeParameters().length != 0 && !type.hasExplicitTypeArguments()) { return null; } if (Collection.class.isAssignableFrom(rawType) || rawType == AtomicReferenceArray.class) { - codec = codec(CodecUtils.elementTypeRef(type)); + codec = childCodec(CodecUtils.elementTypeRef(type)); return codec == null ? null : new SelectedCodec(null, codec, null, null); } if (rawType == Optional.class || rawType == AtomicReference.class) { - codec = codec(CodecUtils.elementTypeRef(type)); + codec = childCodec(CodecUtils.elementTypeRef(type)); return codec == null ? null : new SelectedCodec(null, null, codec, null); } if (Map.class.isAssignableFrom(rawType)) { - codec = codec(CodecUtils.mapKeyValueTypeRefs(type).f1); + codec = childCodec(CodecUtils.mapKeyValueTypeRefs(type).f1); return codec == null ? null : new SelectedCodec(null, null, null, codec); } return null; @@ -207,18 +208,51 @@ private Class> codec(TypeRef type) { if (semantic(type)) { return null; } - return codec((type.isPrimitive() ? type.wrap() : type).getType()); - } - - private Class> codec(Type type) { + TypeRef occurrence = type.isPrimitive() ? type.wrap() : type; for (Entry entry : entries) { - if (sameType(entry.target, type)) { + if (matches(entry.target, occurrence)) { return entry.codecClass; } } return null; } + /** + * Matches a target against an occurrence. A language module may describe a generic array as a raw + * array class with a parameterized component token, so arrays are compared by their components. + */ + private static boolean matches(Type target, TypeRef occurrence) { + if (target instanceof GenericArrayType + && occurrence.getRawType().isArray() + && !(occurrence.getType() instanceof GenericArrayType)) { + return matches( + ((GenericArrayType) target).getGenericComponentType(), occurrence.getComponentType()); + } + return sameType(target, occurrence.getType()); + } + + /** A wildcard child is not concrete, which an explicit child member rejects as well. */ + private Class> childCodec(TypeRef child) { + return child.getType() instanceof WildcardType ? null : codec(child); + } + + /** + * Reads {@code ? extends X} as {@code X}. Kotlin writes declaration-site variance into generic + * signatures, so a codec of {@code List} declares {@code List}. + */ + private static Type covariant(Type type) { + if (type instanceof WildcardType) { + WildcardType wildcard = (WildcardType) type; + // An unbounded wildcard reads as ? extends Object and stays a wildcard: it names no type. + if (wildcard.getLowerBounds().length == 0 + && wildcard.getUpperBounds().length == 1 + && wildcard.getUpperBounds()[0] != Object.class) { + return wildcard.getUpperBounds()[0]; + } + } + return type; + } + private static boolean semantic(TypeRef type) { return type.getTypeExtMeta() != null && type.getTypeExtMeta().typeId() != Types.UNKNOWN; } @@ -252,6 +286,7 @@ private static Type targetType( } private static boolean concrete(Type type) { + type = covariant(type); if (type instanceof Class) { return true; } @@ -275,6 +310,8 @@ private static boolean concrete(Type type) { /** Compares reflected types structurally, independent of their implementation classes. */ private static boolean sameType(Type a, Type b) { + a = covariant(a); + b = covariant(b); if (a instanceof Class || b instanceof Class) { return a.equals(b); } diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index f576c238c3..8c8e43936a 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -827,7 +827,21 @@ public void wildcardChildrenKeepTheirMapping() { assertEquals(newJson().toJson(value), "{\"prices\":[1E+1]}"); } - @JsonDefaultCodec(TaggedDecimalCodec.class) + public static final class TreeNodeCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, TreeNode value) { + writer.writeString("node"); + } + + @Override + public TreeNode read(JsonReader reader) { + reader.readString(); + return new TreeNode(); + } + } + + /** The TreeNode default makes List select a child default, so ownership is checked. */ + @JsonDefaultCodec({TaggedDecimalCodec.class, TreeNodeCodec.class}) public static class TreeNode { public BigDecimal value; public List children; diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt index 6e102be7d9..1b725dcf47 100644 --- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt +++ b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt @@ -63,14 +63,18 @@ internal class ForyJsonKotlinSymbolProcessor(environment: SymbolProcessorEnviron sequenceOf(JSON_DEFAULT_CODEC_NAME, "$JSON_DEFAULT_CODEC_NAME.List") .flatMap(resolver::getSymbolsWithAnnotation) .filterIsInstance() - .filter { it.classKind == ClassKind.INTERFACE } + .filter { + it.classKind == ClassKind.INTERFACE || + it.classKind == ClassKind.ENUM_CLASS || + it.classKind == ClassKind.ANNOTATION_CLASS + } .filter { declaration -> declaration.annotations.none { it.annotationType.resolve().declaration.qualifiedName?.asString() == JSON_MIXIN } } .forEach { - logger.error("@JsonDefaultCodec is read from classes only, not from interfaces", it) + logger.error("@JsonDefaultCodec is read from classes only, not from interfaces, enums, or annotation types", it) } for (symbol in resolver.getSymbolsWithAnnotation(JSON_MIXIN)) { if (!symbol.validate()) { diff --git a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt index cc02ddbc12..59a73c8935 100644 --- a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt +++ b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt @@ -147,6 +147,46 @@ class KotlinBuiltInCodecsTest { assertTrue(error.message.orEmpty().contains("Kotlin unsigned type"), error.message) } + class LongListArrayCodec : AbstractJsonValueCodec>>() { + override fun write(writer: JsonWriter, value: Array>) { + writer.writeString("arrays:${value.size}") + } + + override fun read(reader: JsonReader): Array> { + reader.readString() + return arrayOf(listOf(1L)) + } + } + + @JsonDefaultCodec(LongListArrayCodec::class) + class GenericArrayHolder(val values: Array>) + + class LongListCodec : AbstractJsonValueCodec>() { + override fun write(writer: JsonWriter, value: List) { + writer.writeString("longs:${value.size}") + } + + override fun read(reader: JsonReader): List { + reader.readString() + return listOf(1L) + } + } + + @JsonDefaultCodec(LongListCodec::class) class LongListHolder(val values: List) + + @Test + fun defaultCodecMatchesKotlinCollectionTarget() { + assertEquals("{\"values\":\"longs:2\"}", fory.toJson(LongListHolder(listOf(1L, 2L)))) + } + + @Test + fun defaultCodecMatchesGenericArrayProperty() { + assertEquals( + "{\"values\":\"arrays:2\"}", + fory.toJson(GenericArrayHolder(arrayOf(listOf(1L), listOf(2L)))), + ) + } + @Test fun defaultCodecKeepsUnsignedMapping() { val value = SignedAndUnsigned(5, UInt.MAX_VALUE, listOf(1), listOf(UInt.MAX_VALUE)) From b2c02a7909671588770446046c78ff24e5044aba Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 22:34:01 +0100 Subject: [PATCH 12/26] style(kotlin): format default codec diagnostic Co-Authored-By: Claude Opus 5.5 --- .../fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt index 1b725dcf47..0f22b179cb 100644 --- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt +++ b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/ForyJsonKotlinSymbolProcessor.kt @@ -74,7 +74,10 @@ internal class ForyJsonKotlinSymbolProcessor(environment: SymbolProcessorEnviron } } .forEach { - logger.error("@JsonDefaultCodec is read from classes only, not from interfaces, enums, or annotation types", it) + logger.error( + "@JsonDefaultCodec is read from classes only, not from interfaces, enums, or annotation types", + it + ) } for (symbol in resolver.getSymbolsWithAnnotation(JSON_MIXIN)) { if (!symbol.validate()) { From d93b44d4a245eefd98c4188a9ae000e47d9326e3 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 22:36:29 +0100 Subject: [PATCH 13/26] fix(java): match nested Kotlin generic arrays through occurrence tokens Co-Authored-By: Claude Opus 5.5 --- .../fory/json/resolver/JsonDefaultCodecs.java | 34 +++++++++++++++---- .../json/kotlin/KotlinBuiltInCodecsTest.kt | 22 ++++++++++++ 2 files changed, 50 insertions(+), 6 deletions(-) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 027ce90ca2..e5a8e30b21 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -218,17 +218,39 @@ private Class> codec(TypeRef type) { } /** - * Matches a target against an occurrence. A language module may describe a generic array as a raw - * array class with a parameterized component token, so arrays are compared by their components. + * Matches a target against an occurrence through the occurrence's own tokens. A language module + * may describe a generic array, at any depth, as a raw array class with a parameterized component + * token, so arrays are compared by component and parameterized types argument by argument. */ private static boolean matches(Type target, TypeRef occurrence) { - if (target instanceof GenericArrayType - && occurrence.getRawType().isArray() - && !(occurrence.getType() instanceof GenericArrayType)) { + target = covariant(target); + Type type = occurrence.getType(); + if (type instanceof WildcardType) { + return sameType(target, type); + } + if (target instanceof GenericArrayType && occurrence.getRawType().isArray()) { return matches( ((GenericArrayType) target).getGenericComponentType(), occurrence.getComponentType()); } - return sameType(target, occurrence.getType()); + if (target instanceof ParameterizedType && occurrence.hasExplicitTypeArguments()) { + ParameterizedType parameterized = (ParameterizedType) target; + Type[] arguments = parameterized.getActualTypeArguments(); + List> occurrenceArguments = occurrence.getTypeArguments(); + if (!parameterized.getRawType().equals(occurrence.getRawType()) + || arguments.length != occurrenceArguments.size()) { + return false; + } + for (int i = 0; i < arguments.length; i++) { + if (!matches(arguments[i], occurrenceArguments.get(i))) { + return false; + } + } + Type owner = parameterized.getOwnerType(); + return owner == null + || !(type instanceof ParameterizedType) + || sameType(owner, ((ParameterizedType) type).getOwnerType()); + } + return sameType(target, type); } /** A wildcard child is not concrete, which an explicit child member rejects as well. */ diff --git a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt index 59a73c8935..3ce1a0adfc 100644 --- a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt +++ b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt @@ -179,6 +179,28 @@ class KotlinBuiltInCodecsTest { assertEquals("{\"values\":\"longs:2\"}", fory.toJson(LongListHolder(listOf(1L, 2L)))) } + class NestedArrayCodec : AbstractJsonValueCodec>>>() { + override fun write(writer: JsonWriter, value: List>>) { + writer.writeString("nested:${value.size}") + } + + override fun read(reader: JsonReader): List>> { + reader.readString() + return emptyList() + } + } + + @JsonDefaultCodec(NestedArrayCodec::class) + class NestedArrayHolder(val values: List>>) + + @Test + fun defaultCodecMatchesNestedGenericArrayProperty() { + assertEquals( + "{\"values\":\"nested:1\"}", + fory.toJson(NestedArrayHolder(listOf(arrayOf(listOf(1L))))), + ) + } + @Test fun defaultCodecMatchesGenericArrayProperty() { assertEquals( From 5dc199fc086d2c9c599e0e8d8d45bfc5ae6c4d60 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 22:38:41 +0100 Subject: [PATCH 14/26] test(kotlin): pin creator reads of open elements, mixin over inherited defaults Co-Authored-By: Claude Opus 5.5 --- .../fory/json/JsonDefaultCodecTest.java | 21 +++++++ .../json/kotlin/KotlinBuiltInCodecsTest.kt | 55 +++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index 8c8e43936a..1c90994c64 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -462,6 +462,27 @@ public void mixinRemovalClearsBothDeclarationForms() { @JsonMixinRemove(JsonDefaultCodec.class) public interface ChildWithoutDefaults {} + @JsonDefaultCodec({TaggedDecimalCodec.class, TaggedIntegerCodec.class}) + public static class TwoDefaultsBase { + public BigDecimal price; + public Integer count; + } + + public static class TwoDefaultsChild extends TwoDefaultsBase {} + + @JsonMixin(target = TwoDefaultsChild.class) + @JsonDefaultCodec(OtherDecimalCodec.class) + public interface TwoDefaultsChildMixin {} + + @Test + public void mixinDefaultReplacesOneInheritedTargetAndKeepsTheOther() { + ForyJson json = newJsonBuilder().registerMixin(TwoDefaultsChildMixin.class).build(); + TwoDefaultsChild child = new TwoDefaultsChild(); + child.price = TEN; + child.count = 3; + assertEquals(json.toJson(child), "{\"price\":\"o:10\",\"count\":\"i:3\"}"); + } + @Test public void mixinRemovalOnTargetDropsInheritedDefaults() { ForyJson json = newJsonBuilder().registerMixin(ChildWithoutDefaults.class).build(); diff --git a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt index 3ce1a0adfc..2ca8f54ab6 100644 --- a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt +++ b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt @@ -37,7 +37,10 @@ import kotlin.uuid.ExperimentalUuidApi import kotlin.uuid.Uuid import org.apache.fory.json.ForyJsonException import org.apache.fory.json.annotation.JsonByteArray +import org.apache.fory.json.annotation.JsonCreator import org.apache.fory.json.annotation.JsonDefaultCodec +import org.apache.fory.json.annotation.JsonIgnore +import org.apache.fory.json.annotation.JsonProperty import org.apache.fory.json.codec.AbstractJsonValueCodec import org.apache.fory.json.codec.DirectUnboxedValueCodec import org.apache.fory.json.reader.JsonReader @@ -193,6 +196,58 @@ class KotlinBuiltInCodecsTest { @JsonDefaultCodec(NestedArrayCodec::class) class NestedArrayHolder(val values: List>>) + open class OpenShape(val name: String) { + override fun equals(other: Any?): Boolean = other is OpenShape && name == other.name + + override fun hashCode(): Int = name.hashCode() + } + + class OpenShapeCodec : AbstractJsonValueCodec() { + override fun write(writer: JsonWriter, value: OpenShape) { + writer.writeString("s:${value.name}") + } + + override fun read(reader: JsonReader): OpenShape = OpenShape(reader.readString().substring(2)) + } + + @JsonDefaultCodec(OpenShapeCodec::class) + class ListedCreator + private constructor( + val shapes: List, + val byKey: Map, + @get:JsonIgnore val selected: Boolean, + ) { + @JsonCreator(value = ["shapes", "byKey"]) + constructor( + sourceShapes: List, + sourceByKey: Map, + ) : this(sourceShapes, sourceByKey, true) + } + + @JsonDefaultCodec(OpenShapeCodec::class) + class LocalCreator + @JsonCreator + constructor( + @JsonProperty("shapes") val shapes: List, + @JsonProperty("byKey") val byKey: Map, + ) + + @Test + fun creatorReadsOpenElementsWithTheWrittenDefault() { + for (codegen in listOf(false, true)) { + val json = ForyJsonKotlin.builder().withCodegen(codegen).withAsyncCompilation(false).build() + val text = "{\"shapes\":[\"s:a\"],\"byKey\":{\"k\":\"s:b\"}}" + val listed = json.fromJson(text, ListedCreator::class.java) + assertEquals(listOf(OpenShape("a")), listed.shapes) + assertEquals(mapOf("k" to OpenShape("b")), listed.byKey) + assertEquals(text, json.toJson(listed)) + val local = json.fromJson(text, LocalCreator::class.java) + assertEquals(listOf(OpenShape("a")), local.shapes) + assertEquals(mapOf("k" to OpenShape("b")), local.byKey) + assertEquals(text, json.toJson(local)) + } + } + @Test fun defaultCodecMatchesNestedGenericArrayProperty() { assertEquals( From cb2623a5da1701493bdfa0fff24f0511b03af512 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 22:44:11 +0100 Subject: [PATCH 15/26] fix(java): normalize covariance on targets only, pair container subclass arguments Co-Authored-By: Claude Opus 5.5 --- .../fory/json/resolver/JsonDefaultCodecs.java | 57 ++++++++++---- .../fory/json/JsonDefaultCodecTest.java | 74 +++++++++++++++++++ 2 files changed, 116 insertions(+), 15 deletions(-) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index e5a8e30b21..26f52528e1 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -232,27 +232,43 @@ private static boolean matches(Type target, TypeRef occurrence) { return matches( ((GenericArrayType) target).getGenericComponentType(), occurrence.getComponentType()); } - if (target instanceof ParameterizedType && occurrence.hasExplicitTypeArguments()) { + if (target instanceof ParameterizedType && type instanceof ParameterizedType) { ParameterizedType parameterized = (ParameterizedType) target; + ParameterizedType declared = (ParameterizedType) type; Type[] arguments = parameterized.getActualTypeArguments(); - List> occurrenceArguments = occurrence.getTypeArguments(); - if (!parameterized.getRawType().equals(occurrence.getRawType()) - || arguments.length != occurrenceArguments.size()) { + Type[] declaredArguments = declared.getActualTypeArguments(); + if (!parameterized.getRawType().equals(declared.getRawType()) + || arguments.length != declaredArguments.length) { return false; } + List> tokens = occurrence.getTypeArguments(); for (int i = 0; i < arguments.length; i++) { - if (!matches(arguments[i], occurrenceArguments.get(i))) { + if (!matches(arguments[i], argument(declaredArguments[i], tokens, i, arguments.length))) { return false; } } Type owner = parameterized.getOwnerType(); - return owner == null - || !(type instanceof ParameterizedType) - || sameType(owner, ((ParameterizedType) type).getOwnerType()); + return owner == null || sameType(owner, declared.getOwnerType()); } return sameType(target, type); } + /** + * Returns the occurrence token of one declared type argument. {@code TypeRef} may normalize a + * container subclass's arguments to its element type, so a token is used only when it describes + * the same raw type as the declared argument, as for a Kotlin array with a component token. + */ + private static TypeRef argument(Type declared, List> tokens, int index, int count) { + if (tokens.size() == count) { + TypeRef token = tokens.get(index); + if (CodecUtils.rawType(token.getType(), Object.class) + == CodecUtils.rawType(declared, Object.class)) { + return token; + } + } + return TypeRef.of(declared); + } + /** A wildcard child is not concrete, which an explicit child member rejects as well. */ private Class> childCodec(TypeRef child) { return child.getType() instanceof WildcardType ? null : codec(child); @@ -281,7 +297,7 @@ private static boolean semantic(TypeRef type) { private static Entry find(List entries, Type target) { for (Entry entry : entries) { - if (sameType(entry.target, target)) { + if (sameType(entry.target, target, true)) { return entry; } } @@ -330,10 +346,20 @@ private static boolean concrete(Type type) { return false; } - /** Compares reflected types structurally, independent of their implementation classes. */ - private static boolean sameType(Type a, Type b) { + /** + * Compares a target with a reflected type structurally, independent of their implementation + * classes. Only the target's covariant wildcards read as their bound: Kotlin writes them into a + * codec's declared type, while a property declared {@code List} stays a wildcard. + */ + private static boolean sameType(Type target, Type type) { + return sameType(target, type, false); + } + + private static boolean sameType(Type a, Type b, boolean bothTargets) { a = covariant(a); - b = covariant(b); + if (bothTargets) { + b = covariant(b); + } if (a instanceof Class || b instanceof Class) { return a.equals(b); } @@ -347,7 +373,7 @@ private static boolean sameType(Type a, Type b) { return false; } for (int i = 0; i < leftArguments.length; i++) { - if (!sameType(leftArguments[i], rightArguments[i])) { + if (!sameType(leftArguments[i], rightArguments[i], bothTargets)) { return false; } } @@ -355,12 +381,13 @@ private static boolean sameType(Type a, Type b) { Type rightOwner = right.getOwnerType(); return leftOwner == null || rightOwner == null ? Objects.equals(leftOwner, rightOwner) - : sameType(leftOwner, rightOwner); + : sameType(leftOwner, rightOwner, bothTargets); } if (a instanceof GenericArrayType && b instanceof GenericArrayType) { return sameType( ((GenericArrayType) a).getGenericComponentType(), - ((GenericArrayType) b).getGenericComponentType()); + ((GenericArrayType) b).getGenericComponentType(), + bothTargets); } return a.equals(b); } diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index 1c90994c64..2070f0bd95 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -848,6 +848,80 @@ public void wildcardChildrenKeepTheirMapping() { assertEquals(newJson().toJson(value), "{\"prices\":[1E+1]}"); } + public static final class DecimalListCodec extends AbstractJsonValueCodec> { + @Override + public void write(JsonWriter writer, List value) { + writer.writeString("list:" + value.size()); + } + + @Override + public List read(JsonReader reader) { + reader.readString(); + return Collections.emptyList(); + } + } + + @JsonDefaultCodec(DecimalListCodec.class) + public static class ExactAndWildcardLists { + public List exact; + public List wildcard; + } + + @Test + public void propertyWildcardDoesNotMatchAnExactTarget() { + ExactAndWildcardLists value = new ExactAndWildcardLists(); + value.exact = Collections.singletonList(TEN); + value.wildcard = Collections.singletonList(TEN); + assertEquals(newJson().toJson(value), "{\"exact\":\"list:1\",\"wildcard\":[1E+1]}"); + } + + public static class Bucket extends java.util.ArrayList> {} + + public static final class StringBucketCodec extends AbstractJsonValueCodec> { + @Override + public void write(JsonWriter writer, Bucket value) { + writer.writeString("bucket:" + value.size()); + } + + @Override + public Bucket read(JsonReader reader) { + reader.readString(); + return new Bucket<>(); + } + } + + public static class Dictionary extends java.util.HashMap {} + + public static final class DecimalDictionaryCodec + extends AbstractJsonValueCodec> { + @Override + public void write(JsonWriter writer, Dictionary value) { + writer.writeString("dict:" + value.size()); + } + + @Override + public Dictionary read(JsonReader reader) { + reader.readString(); + return new Dictionary<>(); + } + } + + @JsonDefaultCodec({StringBucketCodec.class, DecimalDictionaryCodec.class}) + public static class TransformedContainers { + public Bucket bucket; + public Dictionary dictionary; + } + + @Test + public void containerSubclassTargetsMatchTheirDeclaredArguments() { + TransformedContainers value = new TransformedContainers(); + value.bucket = new Bucket<>(); + value.bucket.add(Collections.singletonList("a")); + value.dictionary = new Dictionary<>(); + value.dictionary.put("k", TEN); + assertEquals(newJson().toJson(value), "{\"bucket\":\"bucket:1\",\"dictionary\":\"dict:1\"}"); + } + public static final class TreeNodeCodec extends AbstractJsonValueCodec { @Override public void write(JsonWriter writer, TreeNode value) { From 1b0dd690bc3d8ea763c0d038b31299690e4a1295 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 22:45:29 +0100 Subject: [PATCH 16/26] test(java): pin class default precedence over codec registration Co-Authored-By: Claude Opus 5.5 --- .../fory/json/JsonDefaultCodecTest.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index 2070f0bd95..20cea5ddfd 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -922,6 +922,63 @@ public void containerSubclassTargetsMatchTheirDeclaredArguments() { assertEquals(newJson().toJson(value), "{\"bucket\":\"bucket:1\",\"dictionary\":\"dict:1\"}"); } + public static final class Money { + public final long cents; + + public Money(long cents) { + this.cents = cents; + } + } + + public static final class RegisteredMoneyCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, Money value) { + writer.writeString("registered:" + value.cents); + } + + @Override + public Money read(JsonReader reader) { + return new Money(Long.parseLong(reader.readString().substring(11))); + } + } + + public static final class DefaultMoneyCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, Money value) { + writer.writeString("default:" + value.cents); + } + + @Override + public Money read(JsonReader reader) { + return new Money(Long.parseLong(reader.readString().substring(8))); + } + } + + @JsonDefaultCodec(DefaultMoneyCodec.class) + public static class Wallet { + public Money cash; + public List coins; + + @JsonCodec(RegisteredMoneyCodec.class) + public Money declared; + } + + @Test + public void classDefaultWinsOverRegistrationLikeAPropertyCodec() { + ForyJson json = newJsonBuilder().registerCodec(Money.class, new RegisteredMoneyCodec()).build(); + Wallet wallet = new Wallet(); + wallet.cash = new Money(1); + wallet.coins = Collections.singletonList(new Money(2)); + wallet.declared = new Money(3); + String text = json.toJson(wallet); + assertEquals( + text, "{\"cash\":\"default:1\",\"coins\":[\"default:2\"],\"declared\":\"registered:3\"}"); + Wallet read = json.fromJson(text, Wallet.class); + assertEquals(read.cash.cents, 1); + assertEquals(read.coins.get(0).cents, 2); + assertEquals(read.declared.cents, 3); + } + public static final class TreeNodeCodec extends AbstractJsonValueCodec { @Override public void write(JsonWriter writer, TreeNode value) { From 51dcaa08214b3296c788004dc2cf14745fb59391 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 22:49:12 +0100 Subject: [PATCH 17/26] fix(java): use an occurrence token only when it is the declared argument Co-Authored-By: Claude Opus 5.5 --- .../fory/json/resolver/JsonDefaultCodecs.java | 8 ++-- .../fory/json/JsonDefaultCodecTest.java | 48 +++++++++++++++++++ 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 26f52528e1..21a6a7a9fa 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -255,14 +255,14 @@ private static boolean matches(Type target, TypeRef occurrence) { /** * Returns the occurrence token of one declared type argument. {@code TypeRef} may normalize a - * container subclass's arguments to its element type, so a token is used only when it describes - * the same raw type as the declared argument, as for a Kotlin array with a component token. + * container subclass's arguments to its element type, so a token is used only when its reflected + * type is the declared argument itself; it then adds what reflection lacks, such as a Kotlin + * array's parameterized component token. */ private static TypeRef argument(Type declared, List> tokens, int index, int count) { if (tokens.size() == count) { TypeRef token = tokens.get(index); - if (CodecUtils.rawType(token.getType(), Object.class) - == CodecUtils.rawType(declared, Object.class)) { + if (sameType(declared, token.getType(), true)) { return token; } } diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index 20cea5ddfd..5217959437 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -922,6 +922,54 @@ public void containerSubclassTargetsMatchTheirDeclaredArguments() { assertEquals(newJson().toJson(value), "{\"bucket\":\"bucket:1\",\"dictionary\":\"dict:1\"}"); } + public static final class NestedBucketCodec extends AbstractJsonValueCodec>> { + @Override + public void write(JsonWriter writer, Bucket> value) { + writer.writeString("nested:" + value.size()); + } + + @Override + public Bucket> read(JsonReader reader) { + reader.readString(); + return new Bucket<>(); + } + } + + public static final class DeeperBucketCodec + extends AbstractJsonValueCodec>>> { + @Override + public void write(JsonWriter writer, Bucket>> value) { + writer.writeString("deeper:" + value.size()); + } + + @Override + public Bucket>> read(JsonReader reader) { + reader.readString(); + return new Bucket<>(); + } + } + + @JsonDefaultCodec(NestedBucketCodec.class) + public static class NestedBucketHolder { + public Bucket> bucket; + } + + @JsonDefaultCodec(DeeperBucketCodec.class) + public static class DeeperTargetHolder { + public Bucket> bucket; + } + + @Test + public void containerSubclassArgumentsAreNotConfusedWithTheirElementToken() { + Bucket> bucket = new Bucket<>(); + NestedBucketHolder nested = new NestedBucketHolder(); + nested.bucket = bucket; + assertEquals(newJson().toJson(nested), "{\"bucket\":\"nested:0\"}"); + DeeperTargetHolder deeper = new DeeperTargetHolder(); + deeper.bucket = bucket; + assertEquals(newJson().toJson(deeper), "{\"bucket\":[]}"); + } + public static final class Money { public final long cents; From 873fb31902f7e15020bd99124c70f0e3537d0678 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 23:01:26 +0100 Subject: [PATCH 18/26] fix(java): read covariant wildcards as bounds only in Kotlin codec targets Co-Authored-By: Claude Opus 5.5 --- docs/json/custom-codecs.md | 10 +- .../json/annotation/JsonDefaultCodec.java | 10 +- .../fory/json/resolver/JsonDefaultCodecs.java | 122 ++++++++++++++---- .../fory/json/JsonDefaultCodecTest.java | 20 +++ 4 files changed, 127 insertions(+), 35 deletions(-) diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index f078b2d53d..1eb0f19921 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -296,11 +296,13 @@ one class may name at most one codec per target type. A property or creator parameter whose resolved type equals a target uses the codec as if it declared `@JsonCodec(value = ...)`; a primitive property or array element matches its wrapper type. -A target written as `? extends T`, which Kotlin emits for declaration-site variance, reads as `T`. +In a Kotlin codec's declared type, a `? extends T` that Kotlin emits for declaration-site variance +reads as `T`; a Java codec's target must not contain wildcards. -Otherwise a target equal to the direct child of an array, `Collection`, `AtomicReferenceArray`, -`Optional`, `AtomicReference`, or the value of a `Map` fills the matching child member from the -table above, so a `Byte` default writes a `byte[]` as a JSON array of codec values whatever +Otherwise a target equal to the direct child of a Java array, `Collection`, +`AtomicReferenceArray`, `Optional`, `AtomicReference`, or the value of a `Map` fills the matching +child member from the table above; a language module's own containers, such as Scala `Option` or +`Seq`, are not filled, so a `Byte` default writes a `byte[]` as a JSON array of codec values whatever `byteArrayFormat` says. A child is filled only where the container keeps its standard mapping: a registered codec or factory, a module, or a type declaration that owns the container keeps it unchanged. Deeper nesting is not searched, and a wildcard child such as `List` diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java index 9560953fc8..3194ddbe82 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java @@ -36,16 +36,16 @@ *

Each codec targets the type argument it declares for {@link JsonValueCodec}: a codec of {@code * BigDecimal} targets {@code BigDecimal}, a codec of {@code Optional} targets exactly * {@code Optional}. That type must be concrete, without type variables or wildcards, - * except that a covariant {@code ? extends T}, which Kotlin emits, reads as {@code T}. One class - * may name at most one codec per target type. + * except that in a Kotlin codec a covariant {@code ? extends T}, which Kotlin emits, reads as + * {@code T}. One class may name at most one codec per target type. * *

A property or creator parameter whose resolved type equals a target uses that codec as if it * declared {@code @JsonCodec(value = ...)}; a primitive property or array element matches its * wrapper type. Without a whole-type match, a target that equals the direct child of an array, * {@code Collection}, {@code AtomicReferenceArray}, {@code Optional}, {@code AtomicReference}, or - * the value of a {@code Map} is used as the matching {@link JsonCodec} child member, but only where - * the container keeps its standard mapping: a registered codec or factory, a module, or a type - * declaration that owns the container keeps it unchanged. + * the value of a {@code Map} (Java containers only) is used as the matching {@link JsonCodec} child + * member, but only where the container keeps its standard mapping: a registered codec or factory, a + * module, or a type declaration that owns the container keeps it unchanged. * *

A property that declares its own {@link JsonCodec}, {@link JsonFormat}, {@link JsonByteArray}, * {@link JsonRawValue}, or {@link JsonUnwrapped}, and JSON Any properties, do not use defaults. diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 21a6a7a9fa..3cbe7d183a 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -223,7 +223,6 @@ private Class> codec(TypeRef type) { * token, so arrays are compared by component and parameterized types argument by argument. */ private static boolean matches(Type target, TypeRef occurrence) { - target = covariant(target); Type type = occurrence.getType(); if (type instanceof WildcardType) { return sameType(target, type); @@ -262,7 +261,7 @@ private static boolean matches(Type target, TypeRef occurrence) { private static TypeRef argument(Type declared, List> tokens, int index, int count) { if (tokens.size() == count) { TypeRef token = tokens.get(index); - if (sameType(declared, token.getType(), true)) { + if (sameType(declared, token.getType())) { return token; } } @@ -275,29 +274,56 @@ private Class> childCodec(TypeRef child) { } /** - * Reads {@code ? extends X} as {@code X}. Kotlin writes declaration-site variance into generic - * signatures, so a codec of {@code List} declares {@code List}. + * Reads each covariant {@code ? extends T} in a Kotlin codec's declared type as {@code T}. Kotlin + * writes declaration-site variance into generic signatures, so a Kotlin codec of {@code + * List} declares {@code List}; a Java codec's wildcards stay wildcards. */ - private static Type covariant(Type type) { + private static Type kotlinInvariant(Type type) { if (type instanceof WildcardType) { WildcardType wildcard = (WildcardType) type; // An unbounded wildcard reads as ? extends Object and stays a wildcard: it names no type. if (wildcard.getLowerBounds().length == 0 && wildcard.getUpperBounds().length == 1 && wildcard.getUpperBounds()[0] != Object.class) { - return wildcard.getUpperBounds()[0]; + return kotlinInvariant(wildcard.getUpperBounds()[0]); } + return type; + } + if (type instanceof ParameterizedType) { + ParameterizedType parameterized = (ParameterizedType) type; + Type[] arguments = parameterized.getActualTypeArguments().clone(); + for (int i = 0; i < arguments.length; i++) { + arguments[i] = kotlinInvariant(arguments[i]); + } + Type owner = parameterized.getOwnerType(); + return new InvariantParameterizedType( + parameterized.getRawType(), arguments, owner == null ? null : kotlinInvariant(owner)); + } + if (type instanceof GenericArrayType) { + Type component = kotlinInvariant(((GenericArrayType) type).getGenericComponentType()); + return component instanceof Class + ? java.lang.reflect.Array.newInstance((Class) component, 0).getClass() + : new InvariantArrayType(component); } return type; } + private static boolean kotlinClass(Class type) { + for (Annotation annotation : type.getDeclaredAnnotations()) { + if (annotation.annotationType().getName().equals("kotlin.Metadata")) { + return true; + } + } + return false; + } + private static boolean semantic(TypeRef type) { return type.getTypeExtMeta() != null && type.getTypeExtMeta().typeId() != Types.UNKNOWN; } private static Entry find(List entries, Type target) { for (Entry entry : entries) { - if (sameType(entry.target, target, true)) { + if (sameType(entry.target, target)) { return entry; } } @@ -313,6 +339,9 @@ private static Type targetType( List> arguments = ((TypeRef) TypeRef.of(codecClass)).getSupertype(JsonValueCodec.class).getTypeArguments(); Type target = arguments.size() == 1 ? arguments.get(0).getType() : null; + if (target != null && kotlinClass(codecClass)) { + target = kotlinInvariant(target); + } if (target == null || !concrete(target)) { throw invalid(declaring, codecClass, "does not declare a concrete value type"); } @@ -324,7 +353,6 @@ private static Type targetType( } private static boolean concrete(Type type) { - type = covariant(type); if (type instanceof Class) { return true; } @@ -346,20 +374,8 @@ private static boolean concrete(Type type) { return false; } - /** - * Compares a target with a reflected type structurally, independent of their implementation - * classes. Only the target's covariant wildcards read as their bound: Kotlin writes them into a - * codec's declared type, while a property declared {@code List} stays a wildcard. - */ - private static boolean sameType(Type target, Type type) { - return sameType(target, type, false); - } - - private static boolean sameType(Type a, Type b, boolean bothTargets) { - a = covariant(a); - if (bothTargets) { - b = covariant(b); - } + /** Compares reflected types structurally, independent of their implementation classes. */ + private static boolean sameType(Type a, Type b) { if (a instanceof Class || b instanceof Class) { return a.equals(b); } @@ -373,7 +389,7 @@ private static boolean sameType(Type a, Type b, boolean bothTargets) { return false; } for (int i = 0; i < leftArguments.length; i++) { - if (!sameType(leftArguments[i], rightArguments[i], bothTargets)) { + if (!sameType(leftArguments[i], rightArguments[i])) { return false; } } @@ -381,13 +397,12 @@ private static boolean sameType(Type a, Type b, boolean bothTargets) { Type rightOwner = right.getOwnerType(); return leftOwner == null || rightOwner == null ? Objects.equals(leftOwner, rightOwner) - : sameType(leftOwner, rightOwner, bothTargets); + : sameType(leftOwner, rightOwner); } if (a instanceof GenericArrayType && b instanceof GenericArrayType) { return sameType( ((GenericArrayType) a).getGenericComponentType(), - ((GenericArrayType) b).getGenericComponentType(), - bothTargets); + ((GenericArrayType) b).getGenericComponentType()); } return a.equals(b); } @@ -402,6 +417,61 @@ private static ForyJsonException invalid(Class declaring, Class codecClass + reason); } + /** A Kotlin codec target with its covariant wildcards read as their bounds. */ + private static final class InvariantParameterizedType implements ParameterizedType { + private final Type rawType; + private final Type[] arguments; + private final Type ownerType; + + private InvariantParameterizedType(Type rawType, Type[] arguments, Type ownerType) { + this.rawType = rawType; + this.arguments = arguments; + this.ownerType = ownerType; + } + + @Override + public Type[] getActualTypeArguments() { + return arguments.clone(); + } + + @Override + public Type getRawType() { + return rawType; + } + + @Override + public Type getOwnerType() { + return ownerType; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(rawType.getTypeName()).append('<'); + for (int i = 0; i < arguments.length; i++) { + builder.append(i == 0 ? "" : ", ").append(arguments[i].getTypeName()); + } + return builder.append('>').toString(); + } + } + + private static final class InvariantArrayType implements GenericArrayType { + private final Type component; + + private InvariantArrayType(Type component) { + this.component = component; + } + + @Override + public Type getGenericComponentType() { + return component; + } + + @Override + public String toString() { + return component.getTypeName() + "[]"; + } + } + private static final class Entry { private final Type target; private final Class> codecClass; diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index 5217959437..fdf732c3f7 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -1077,6 +1077,24 @@ public List read(JsonReader reader) { assertEquals(json.toJson(node), "{\"value\":\"d:10\",\"children\":\"list:1\"}"); } + public static final class BoundedListCodec + extends AbstractJsonValueCodec> { + @Override + public void write(JsonWriter writer, List value) { + writer.writeNull(); + } + + @Override + public List read(JsonReader reader) { + return null; + } + } + + @JsonDefaultCodec(BoundedListCodec.class) + public static class BoundedWildcardTarget { + public List numbers; + } + @JsonDefaultCodec({TaggedDecimalCodec.class, OtherDecimalCodec.class}) public static class DuplicateTarget { public BigDecimal price; @@ -1103,6 +1121,8 @@ public void invalidDeclarations() { assertInvalid(json, ImplementsThroughSuperinterface.class, "not from interface"); assertInvalid(json, ImplementsThroughSuperclass.class, "not from interface"); assertInvalid(json, SentinelTarget.class, "is not a codec"); + // Only a Kotlin codec's declaration-site variance reads as its bound. + assertInvalid(json, BoundedWildcardTarget.class, "does not declare a concrete value type"); } private static void assertInvalid(ForyJson json, Class type, String message) { From c7b91d0d1a6b0e698af53d09bfde9404ca377b7f Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 23:06:32 +0100 Subject: [PATCH 19/26] fix(java): compare raw array targets by component token Co-Authored-By: Claude Opus 5.5 --- .../fory/json/resolver/JsonDefaultCodecs.java | 13 ++++++-- .../fory/json/JsonDefaultCodecTest.java | 31 +++++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 3cbe7d183a..1583011ad5 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -227,9 +227,16 @@ private static boolean matches(Type target, TypeRef occurrence) { if (type instanceof WildcardType) { return sameType(target, type); } - if (target instanceof GenericArrayType && occurrence.getRawType().isArray()) { - return matches( - ((GenericArrayType) target).getGenericComponentType(), occurrence.getComponentType()); + if (occurrence.getRawType().isArray()) { + // Compare by component for raw and generic array targets alike: an occurrence token may + // carry a parameterized component that its raw array class does not show. + if (target instanceof GenericArrayType) { + return matches( + ((GenericArrayType) target).getGenericComponentType(), occurrence.getComponentType()); + } + if (target instanceof Class && ((Class) target).isArray()) { + return matches(((Class) target).getComponentType(), occurrence.getComponentType()); + } } if (target instanceof ParameterizedType && type instanceof ParameterizedType) { ParameterizedType parameterized = (ParameterizedType) target; diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index fdf732c3f7..9aea52d8a1 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -970,6 +970,37 @@ public void containerSubclassArgumentsAreNotConfusedWithTheirElementToken() { assertEquals(newJson().toJson(deeper), "{\"bucket\":[]}"); } + @SuppressWarnings("rawtypes") + public static final class RawListArrayCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, List[] value) { + writer.writeNull(); + } + + @Override + public List[] read(JsonReader reader) { + return null; + } + } + + @JsonDefaultCodec(RawListArrayCodec.class) + public static class RawListArrayDefaults {} + + @Test + @SuppressWarnings("rawtypes") + public void rawArrayTargetComparesComponentTokens() { + org.apache.fory.json.resolver.JsonDefaultCodecs defaults = + org.apache.fory.json.resolver.JsonDefaultCodecs.of( + RawListArrayDefaults.class, + new org.apache.fory.json.resolver.JsonSharedRegistry(newJsonBuilder().buildConfig())); + // A language module may describe Array> as List[] with a parameterized component. + org.apache.fory.reflect.TypeRef kotlinStyle = + org.apache.fory.reflect.TypeRef.of( + List[].class, null, null, new org.apache.fory.reflect.TypeRef>() {}); + assertEquals(defaults.select(kotlinStyle), null); + assertTrue(defaults.select(org.apache.fory.reflect.TypeRef.of(List[].class)) != null); + } + public static final class Money { public final long cents; From 48a214ec917e3a377a9ebbd62e723f5b929f13b3 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 23:08:01 +0100 Subject: [PATCH 20/26] fix(java): select creator defaults from the logical property type, read Kotlin variance across the codec chain Co-Authored-By: Claude Opus 5.5 --- docs/json/custom-codecs.md | 5 +++-- .../fory/json/codec/ObjectCodecBuilder.java | 17 +++++++++++++---- .../fory/json/resolver/JsonDefaultCodecs.java | 16 +++++++++++----- .../fory/json/kotlin/KotlinBuiltInCodecsTest.kt | 16 ++++++++++++++++ 4 files changed, 43 insertions(+), 11 deletions(-) diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index 1eb0f19921..2557598ab4 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -296,7 +296,7 @@ one class may name at most one codec per target type. A property or creator parameter whose resolved type equals a target uses the codec as if it declared `@JsonCodec(value = ...)`; a primitive property or array element matches its wrapper type. -In a Kotlin codec's declared type, a `? extends T` that Kotlin emits for declaration-site variance +In the declared type of a codec with a Kotlin class on its superclass chain, a `? extends T` that Kotlin emits for declaration-site variance reads as `T`; a Java codec's target must not contain wildcards. Otherwise a target equal to the direct child of a Java array, `Collection`, @@ -310,7 +310,8 @@ keeps its mapping, as an explicit child member would reject it. A default codec is used exactly like a property `JsonCodec`, so it receives and owns null as described above for every property it reaches. Properties that declare `JsonCodec`, `JsonFormat`, -`JsonByteArray`, `JsonRawValue`, or `JsonUnwrapped`, and JSON Any properties, do not use defaults. +`JsonByteArray`, `JsonRawValue`, or `JsonUnwrapped`, and JSON Any properties, do not use defaults; +there is no separate per-property opt-out. A value-class property read and written through its unboxed carrier cannot take a codec, so a default that matches one fails like a declared `JsonCodec`; a nullable or container occurrence of the value class is boxed and uses the default. A target that is a Kotlin unsigned type, which the 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 de075d0131..d2d02a0ef8 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 @@ -1561,7 +1561,7 @@ private static JsonCreatorInfo buildRecordCreatorInfo( i, resolved, rawTypes[i], - builder.effectiveCodec(resolved), + builder.creatorCodec(resolved, ownerType), builder.valueCodecClass(), builder.formatAnnotation(), builder.creatorUnboxedRequired, @@ -1694,7 +1694,7 @@ private static JsonCreatorInfo buildCreatorInfo( } if (!builder.isAny() && builder.unwrappedAnnotation == null) { TypeRef resolved = ownerType.resolveType(parameterTypes[i]); - JsonCodec codecAnnotation = builder.effectiveCodec(resolved); + JsonCodec codecAnnotation = builder.creatorCodec(resolved, ownerType); Class> valueCodecClass = builder.valueCodecClass(); fields.add( new JsonCreatorFieldInfo( @@ -1781,7 +1781,7 @@ private static JsonCreatorInfo buildCreatorInfo( codecAnnotation = annotations.defaultCodecs.select(resolved); } } else { - codecAnnotation = builder.effectiveCodec(resolved); + codecAnnotation = builder.creatorCodec(resolved, ownerType); } if (unwrapped != null) { if (builder == null @@ -1963,7 +1963,7 @@ private static JsonCreatorInfo buildObjectModelCreatorInfo( i, resolved, rawTypes[i], - builder.effectiveCodec(resolved), + builder.creatorCodec(resolved, ownerType), builder.valueCodecClass(), builder.formatAnnotation(), builder.creatorUnboxedRequired, @@ -3529,6 +3529,15 @@ private JsonCodec effectiveCodec(TypeRef type) { return usesDefaultCodec() ? annotations.defaultCodecs.select(type) : codecAnnotation; } + /** + * Returns the creator parameter's codec. A property that also has a field or accessor selects + * its default from that logical type, so reading and writing always use the same default. + */ + private JsonCodec creatorCodec(TypeRef parameterType, TypeRef ownerType) { + return effectiveCodec( + usesDefaultCodec() && hasLogicalMember() ? logicalTypeRef(ownerType) : parameterType); + } + private boolean usesDefaultCodec() { return !annotations.defaultCodecs.isEmpty() && codecAnnotation == null diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 1583011ad5..8172c32472 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -315,10 +315,16 @@ private static Type kotlinInvariant(Type type) { return type; } - private static boolean kotlinClass(Class type) { - for (Annotation annotation : type.getDeclaredAnnotations()) { - if (annotation.annotationType().getName().equals("kotlin.Metadata")) { - return true; + /** + * Returns whether any class on the codec's superclass chain is Kotlin. The target is resolved + * through that whole chain, so a Kotlin base class can contribute the variance wildcards. + */ + private static boolean kotlinCodec(Class codecClass) { + for (Class type = codecClass; type != null; type = type.getSuperclass()) { + for (Annotation annotation : type.getDeclaredAnnotations()) { + if (annotation.annotationType().getName().equals("kotlin.Metadata")) { + return true; + } } } return false; @@ -346,7 +352,7 @@ private static Type targetType( List> arguments = ((TypeRef) TypeRef.of(codecClass)).getSupertype(JsonValueCodec.class).getTypeArguments(); Type target = arguments.size() == 1 ? arguments.get(0).getType() : null; - if (target != null && kotlinClass(codecClass)) { + if (target != null && kotlinCodec(codecClass)) { target = kotlinInvariant(target); } if (target == null || !concrete(target)) { diff --git a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt index 2ca8f54ab6..5d3272a0f7 100644 --- a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt +++ b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt @@ -264,6 +264,22 @@ class KotlinBuiltInCodecsTest { ) } + @JsonDefaultCodec(TaggedIntCodec::class) + class UnsignedCreator + private constructor(val signed: Int, val unsigned: UInt, @get:JsonIgnore val selected: Boolean) { + @JsonCreator(value = ["signed", "unsigned"]) + constructor(sourceSigned: Int, sourceUnsigned: UInt) : this(sourceSigned, sourceUnsigned, true) + } + + @Test + fun explicitCreatorKeepsUnsignedMapping() { + val text = "{\"signed\":\"i:5\",\"unsigned\":4294967295}" + val value = fory.fromJson(text, UnsignedCreator::class.java) + assertEquals(5, value.signed) + assertEquals(UInt.MAX_VALUE, value.unsigned) + assertEquals(text, fory.toJson(value)) + } + @Test fun defaultCodecKeepsUnsignedMapping() { val value = SignedAndUnsigned(5, UInt.MAX_VALUE, listOf(1), listOf(UInt.MAX_VALUE)) From 7fc1c0fd7d00534fd31bfa3b0bbb6efffbbf9425 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 23:20:33 +0100 Subject: [PATCH 21/26] ci(kotlin): expect consumer rules of the default codec corpus models Co-Authored-By: Claude Opus 5.5 --- ci/tasks/kotlin.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ci/tasks/kotlin.py b/ci/tasks/kotlin.py index 24f70829f7..73b846618b 100644 --- a/ci/tasks/kotlin.py +++ b/ci/tasks/kotlin.py @@ -35,9 +35,12 @@ "PlatformAccount", "PlatformBox", "PlatformCircle", + "PlatformContainerDefaults", + "PlatformDefaultCodecs", "PlatformDefaults", "PlatformDirectOverride", "PlatformId", + "PlatformInheritedDefaults", "PlatformMarker", "PlatformNullHandling", "PlatformOpen", @@ -48,6 +51,7 @@ CORPUS_MIXIN_TARGETS = { "PlatformDefaultMixin": "PlatformDefaultTarget", "PlatformJavaProfileMixin": "PlatformJavaProfile", + "PlatformMixinDefaults": "PlatformMixinDefaultsTarget", "PlatformMixinOverrideAnnotations": "PlatformMixinOverride", } From 6a563c8cc60831280a3356a8191cf2b34f3d307e Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 23:34:47 +0100 Subject: [PATCH 22/26] fix(java): carry default codec selections without implementing JsonCodec R8 treats a program class that implements an annotation interface as its only implementation and devirtualizes annotation member calls to it, which broke @JsonCodec(keyCodec = ...) in shrunk Android builds. Co-Authored-By: Claude Opus 5.5 --- .../fory/json/codec/ObjectCodecBuilder.java | 50 +++++------ .../fory/json/meta/JsonCreatorFieldInfo.java | 45 ++++++++-- .../apache/fory/json/meta/JsonFieldInfo.java | 24 ++++-- .../fory/json/resolver/JsonDefaultCodecs.java | 83 +++++-------------- .../fory/json/resolver/JsonTypeResolver.java | 58 +++++++++++-- 5 files changed, 150 insertions(+), 110 deletions(-) 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 d2d02a0ef8..798a1c6a0b 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 @@ -1561,7 +1561,8 @@ private static JsonCreatorInfo buildRecordCreatorInfo( i, resolved, rawTypes[i], - builder.creatorCodec(resolved, ownerType), + builder.codecAnnotation(), + builder.creatorDefault(resolved, ownerType), builder.valueCodecClass(), builder.formatAnnotation(), builder.creatorUnboxedRequired, @@ -1694,7 +1695,7 @@ private static JsonCreatorInfo buildCreatorInfo( } if (!builder.isAny() && builder.unwrappedAnnotation == null) { TypeRef resolved = ownerType.resolveType(parameterTypes[i]); - JsonCodec codecAnnotation = builder.creatorCodec(resolved, ownerType); + JsonCodec codecAnnotation = builder.codecAnnotation(); Class> valueCodecClass = builder.valueCodecClass(); fields.add( new JsonCreatorFieldInfo( @@ -1703,6 +1704,7 @@ private static JsonCreatorInfo buildCreatorInfo( resolved, rawTypes[i], codecAnnotation, + builder.creatorDefault(resolved, ownerType), valueCodecClass, builder.formatAnnotation(), builder.creatorUnboxedRequired, @@ -1776,13 +1778,12 @@ private static JsonCreatorInfo buildCreatorInfo( builder == null ? annotations.get(parameters[i], JsonUnwrapped.class) : builder.unwrappedAnnotation; - if (builder == null) { - if (codecAnnotation == null && formatAnnotation == null && unwrapped == null) { - codecAnnotation = annotations.defaultCodecs.select(resolved); - } - } else { - codecAnnotation = builder.creatorCodec(resolved, ownerType); - } + JsonDefaultCodecs.Selection defaultCodec = + builder != null + ? builder.creatorDefault(resolved, ownerType) + : codecAnnotation == null && formatAnnotation == null && unwrapped == null + ? annotations.defaultCodecs.select(resolved) + : null; if (unwrapped != null) { if (builder == null && (property.onNullRead() != NullHandling.DEFAULT @@ -1818,6 +1819,7 @@ private static JsonCreatorInfo buildCreatorInfo( resolved, rawTypes[i], codecAnnotation, + defaultCodec, valueCodecClass, formatAnnotation, false, @@ -1963,7 +1965,8 @@ private static JsonCreatorInfo buildObjectModelCreatorInfo( i, resolved, rawTypes[i], - builder.creatorCodec(resolved, ownerType), + builder.codecAnnotation(), + builder.creatorDefault(resolved, ownerType), builder.valueCodecClass(), builder.formatAnnotation(), builder.creatorUnboxedRequired, @@ -3433,9 +3436,8 @@ private JsonFieldInfo build( readAccessor, ownerType, objectModelType, - usesDefaultCodec() - ? annotations.defaultCodecs.select(logicalTypeRef(ownerType)) - : codecAnnotation, + codecAnnotation, + usesDefaultCodec() ? annotations.defaultCodecs.select(logicalTypeRef(ownerType)) : null, valueCodecClass, formatAnnotation, rawValue, @@ -3523,19 +3525,17 @@ private JsonCodec codecAnnotation() { } /** - * Returns the declared codec, or the class default for {@code type} when nothing is declared. - */ - private JsonCodec effectiveCodec(TypeRef type) { - return usesDefaultCodec() ? annotations.defaultCodecs.select(type) : codecAnnotation; - } - - /** - * Returns the creator parameter's codec. A property that also has a field or accessor selects - * its default from that logical type, so reading and writing always use the same default. + * Returns the class default for a creator parameter, or null when the property declares its own + * representation. A property that also has a field or accessor selects from that logical type, + * so reading and writing use the same default. */ - private JsonCodec creatorCodec(TypeRef parameterType, TypeRef ownerType) { - return effectiveCodec( - usesDefaultCodec() && hasLogicalMember() ? logicalTypeRef(ownerType) : parameterType); + private JsonDefaultCodecs.Selection creatorDefault( + TypeRef parameterType, TypeRef ownerType) { + if (!usesDefaultCodec()) { + return null; + } + return annotations.defaultCodecs.select( + hasLogicalMember() ? logicalTypeRef(ownerType) : parameterType); } private boolean usesDefaultCodec() { 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 5fbe7230bd..94b9493496 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 @@ -47,6 +47,7 @@ public final class JsonCreatorFieldInfo { private final TypeRef typeRef; private final Class rawType; private final JsonCodec codecAnnotation; + private final JsonDefaultCodecs.Selection defaultCodec; private final Class> valueCodecClass; private final JsonFormat formatAnnotation; private final boolean unboxedRequired; @@ -68,6 +69,32 @@ public JsonCreatorFieldInfo( boolean unboxedRequired, NullHandling onNullRead, NullHandling onContentNullRead) { + this( + name, + argumentIndex, + typeRef, + rawType, + codecAnnotation, + null, + valueCodecClass, + formatAnnotation, + unboxedRequired, + onNullRead, + onContentNullRead); + } + + public JsonCreatorFieldInfo( + String name, + int argumentIndex, + TypeRef typeRef, + Class rawType, + JsonCodec codecAnnotation, + JsonDefaultCodecs.Selection defaultCodec, + Class> valueCodecClass, + JsonFormat formatAnnotation, + boolean unboxedRequired, + NullHandling onNullRead, + NullHandling onContentNullRead) { this.onNullRead = onNullRead; this.onContentNullRead = onContentNullRead; this.name = name; @@ -76,10 +103,15 @@ public JsonCreatorFieldInfo( this.typeRef = typeRef; this.rawType = rawType; this.codecAnnotation = codecAnnotation; + this.defaultCodec = defaultCodec; this.valueCodecClass = valueCodecClass; this.formatAnnotation = formatAnnotation; this.unboxedRequired = unboxedRequired; - selectedCodec = codecAnnotation != null || valueCodecClass != null || formatAnnotation != null; + selectedCodec = + codecAnnotation != null + || defaultCodec != null + || valueCodecClass != null + || formatAnnotation != null; } public String name() { @@ -113,6 +145,7 @@ public JsonCreatorFieldInfo withName(String transformedName) { typeRef, rawType, codecAnnotation, + defaultCodec, valueCodecClass, formatAnnotation, unboxedRequired, @@ -159,7 +192,7 @@ public void resolveType(JsonTypeResolver resolver) { + name + " cannot select a codec or format for the unboxed logical type " + typeRef - + JsonDefaultCodecs.origin(codecAnnotation)); + + (defaultCodec == null ? "" : " selected by the class @JsonDefaultCodec")); } JsonTypeInfo canonical = resolver.withContentNullRead(resolver.getTypeInfo(typeRef), onContentNullRead); @@ -189,9 +222,11 @@ public void resolveType(JsonTypeResolver resolver) { private JsonTypeInfo selectedTypeInfo(JsonTypeResolver resolver) { return codecAnnotation != null ? resolver.getTypeInfo(typeRef, codecAnnotation) - : valueCodecClass != null - ? resolver.getTypeInfo(typeRef, valueCodecClass) - : resolver.getTypeInfo(typeRef, formatAnnotation); + : defaultCodec != null + ? resolver.getTypeInfo(typeRef, defaultCodec) + : valueCodecClass != null + ? resolver.getTypeInfo(typeRef, valueCodecClass) + : resolver.getTypeInfo(typeRef, formatAnnotation); } public Object readLatin1(Latin1JsonReader reader) { diff --git a/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonFieldInfo.java index 43b2257d02..34459d3e4e 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 @@ -117,6 +117,7 @@ public final class JsonFieldInfo { private final TypeRef readTypeRef; private final Class readRawType; private final JsonCodec codecAnnotation; + private final JsonDefaultCodecs.Selection defaultCodec; private final Class> valueCodecClass; private final JsonFormat formatAnnotation; private final boolean writeUnboxedRequired; @@ -410,6 +411,7 @@ public JsonFieldInfo( TypeRef ownerType, TypeRef objectModelType, JsonCodec codecAnnotation, + JsonDefaultCodecs.Selection defaultCodec, Class> valueCodecClass, JsonFormat formatAnnotation, boolean rawValue, @@ -464,6 +466,7 @@ public JsonFieldInfo( readIndexAndWriteNull |= OMIT_EMPTY_MASK; } this.codecAnnotation = codecAnnotation; + this.defaultCodec = defaultCodec; this.valueCodecClass = valueCodecClass; this.formatAnnotation = formatAnnotation; this.writeAccessor = writeAccessor; @@ -593,6 +596,7 @@ public JsonFieldInfo withName(String transformedName, TypeRef ownerType) { ownerType, writeTypeRef != null ? writeTypeRef : readTypeRef, codecAnnotation, + defaultCodec, valueCodecClass, formatAnnotation, writesRawString(), @@ -915,23 +919,28 @@ private static boolean requiresCarrier( public void resolveTypes(JsonTypeResolver typeResolver) { TypeRef codecType = writeTypeRef == null ? readTypeRef : writeTypeRef; boolean selectedCodec = - codecAnnotation != null || valueCodecClass != null || formatAnnotation != null; + codecAnnotation != null + || defaultCodec != null + || valueCodecClass != null + || formatAnnotation != null; if (selectedCodec && (writeUnboxedRequired || readUnboxedRequired)) { throw new ForyJsonException( "JSON property " + name + " cannot select a codec or format for the unboxed logical type " + codecType - + JsonDefaultCodecs.origin(codecAnnotation)); + + (defaultCodec == null ? "" : " selected by the class @JsonDefaultCodec")); } JsonTypeInfo selectedTypeInfo = codecAnnotation != null ? typeResolver.getTypeInfo(codecType, codecAnnotation) - : valueCodecClass != null - ? typeResolver.getTypeInfo(codecType, valueCodecClass) - : formatAnnotation != null - ? typeResolver.getTypeInfo(codecType, formatAnnotation) - : null; + : defaultCodec != null + ? typeResolver.getTypeInfo(codecType, defaultCodec) + : valueCodecClass != null + ? typeResolver.getTypeInfo(codecType, valueCodecClass) + : formatAnnotation != null + ? typeResolver.getTypeInfo(codecType, formatAnnotation) + : null; boolean rawString = writeKindId == KIND_RAW_STRING; if (writeRawType != null) { JsonTypeInfo writeOccurrenceTypeInfo; @@ -1264,6 +1273,7 @@ public JsonCreatorFieldInfo asCreatorField(int argumentIndex) { readTypeRef, readRawType, codecAnnotation, + defaultCodec, valueCodecClass, formatAnnotation, readUnboxedRequired, diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 8172c32472..be9721f697 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -39,7 +39,6 @@ import org.apache.fory.json.annotation.JsonDefaultCodec; import org.apache.fory.json.codec.CodecUtils; import org.apache.fory.json.codec.JsonValueCodec; -import org.apache.fory.json.codec.MapKeyCodec; import org.apache.fory.reflect.TypeRef; import org.apache.fory.type.Types; @@ -150,14 +149,14 @@ public boolean isEmpty() { return entries.length == 0; } - /** Returns the codec configuration for a property of {@code type}, or null without a match. */ - public JsonCodec select(TypeRef type) { + /** Returns the codecs a property of {@code type} defaults to, or null without a match. */ + public Selection select(TypeRef type) { if (entries.length == 0) { return null; } Class> codec = codec(type); if (codec != null) { - return new SelectedCodec(codec, null, null, null); + return new Selection(codec, null, null, null); } if (semantic(type)) { return null; @@ -165,40 +164,26 @@ public JsonCodec select(TypeRef type) { Class rawType = type.getRawType(); if (rawType.isArray()) { codec = childCodec(type.getComponentType()); - return codec == null ? null : new SelectedCodec(null, codec, null, null); + return codec == null ? null : new Selection(null, codec, null, null); } if (rawType.getTypeParameters().length != 0 && !type.hasExplicitTypeArguments()) { return null; } if (Collection.class.isAssignableFrom(rawType) || rawType == AtomicReferenceArray.class) { codec = childCodec(CodecUtils.elementTypeRef(type)); - return codec == null ? null : new SelectedCodec(null, codec, null, null); + return codec == null ? null : new Selection(null, codec, null, null); } if (rawType == Optional.class || rawType == AtomicReference.class) { codec = childCodec(CodecUtils.elementTypeRef(type)); - return codec == null ? null : new SelectedCodec(null, null, codec, null); + return codec == null ? null : new Selection(null, null, codec, null); } if (Map.class.isAssignableFrom(rawType)) { codec = childCodec(CodecUtils.mapKeyValueTypeRefs(type).f1); - return codec == null ? null : new SelectedCodec(null, null, null, codec); + return codec == null ? null : new Selection(null, null, null, codec); } return null; } - /** Names a class default as the source of {@code annotation} in an error, or returns "". */ - public static String origin(JsonCodec annotation) { - return annotation instanceof SelectedCodec ? " selected by the class @JsonDefaultCodec" : ""; - } - - /** - * Returns whether {@code annotation} is a default that fills a child member. The resolver keeps - * the container's own mapping when it is not the standard container representation. - */ - static boolean selectsChild(JsonCodec annotation) { - return annotation instanceof SelectedCodec - && annotation.value() == JsonCodec.NoJsonValueCodec.class; - } - /** * Returns the default for one occurrence. A primitive matches its wrapper, but a type a language * module tags with its own semantic type, such as a Kotlin {@code UInt} carried as {@code int}, @@ -495,14 +480,19 @@ private Entry(Type target, Class> codecClass) { } } - /** {@link JsonCodec} configuration selected by a default rather than declared on a property. */ - private static final class SelectedCodec implements JsonCodec { + /** + * Codecs a class default selects for one occurrence. It deliberately does not implement {@link + * JsonCodec}: a program class implementing an annotation interface lets a shrinker such as R8 + * devirtualize every annotation member call to it, breaking real annotation instances. + */ + @Internal + public static final class Selection { private final Class> value; private final Class> elementCodec; private final Class> contentCodec; private final Class> valueCodec; - private SelectedCodec( + private Selection( Class> value, Class> elementCodec, Class> contentCodec, @@ -518,61 +508,26 @@ private static Class> orNone( return codec == null ? JsonCodec.NoJsonValueCodec.class : codec; } - @Override + /** Returns the complete-value codec, or {@code NoJsonValueCodec} for a child selection. */ public Class> value() { return value; } - @Override public Class> elementCodec() { return elementCodec; } - @Override public Class> contentCodec() { return contentCodec; } - @Override - public Class keyCodec() { - return JsonCodec.NoMapKeyCodec.class; - } - - @Override public Class> valueCodec() { return valueCodec; } - @Override - public Class annotationType() { - return JsonCodec.class; - } - - // Annotation contract: equal to any JsonCodec with the same member values. - @Override - public boolean equals(Object other) { - if (!(other instanceof JsonCodec)) { - return false; - } - JsonCodec that = (JsonCodec) other; - return value == that.value() - && elementCodec == that.elementCodec() - && contentCodec == that.contentCodec() - && that.keyCodec() == JsonCodec.NoMapKeyCodec.class - && valueCodec == that.valueCodec(); - } - - @Override - public int hashCode() { - return member("value", value) - + member("elementCodec", elementCodec) - + member("contentCodec", contentCodec) - + member("keyCodec", JsonCodec.NoMapKeyCodec.class) - + member("valueCodec", valueCodec); - } - - private static int member(String name, Class value) { - return (127 * name.hashCode()) ^ value.hashCode(); + /** Returns whether this selection fills a child member rather than the complete value. */ + public boolean child() { + return value == JsonCodec.NoJsonValueCodec.class; } @Override 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 4b11e5def4..5835505956 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 @@ -419,16 +419,38 @@ public JsonTypeInfo getTypeInfo(TypeRef declaredType, JsonCodec annotation) { if (annotation == null) { return getTypeInfo(declaredType); } + ResolutionSnapshot snapshot = beginResolution(); + try { + JsonTypeInfo result = resolveTypeInfo(declaredType, annotation); + completeResolution(snapshot); + return result; + } catch (RuntimeException | Error e) { + rollbackResolution(snapshot); + throw e; + } finally { + endResolution(); + } + } + + /** Resolves the codecs a class {@code JsonDefaultCodec} selected for one occurrence. */ + @Internal + public JsonTypeInfo getTypeInfo(TypeRef declaredType, JsonDefaultCodecs.Selection selection) { ResolutionSnapshot snapshot = beginResolution(); try { // A class default fills a child only where the container keeps its standard mapping, so a // registration, factory, module, or type declaration that owns the container still wins. // The check runs inside the snapshot because a module factory may resolve child types. JsonTypeInfo result = - JsonDefaultCodecs.selectsChild(annotation) - && sharedRegistry.ownsContainer(declaredType, this) + selection.child() && sharedRegistry.ownsContainer(declaredType, this) ? getTypeInfo(declaredType) - : resolveTypeInfo(declaredType, annotation); + : resolveTypeInfo( + declaredType, + null, + selection.value(), + selection.elementCodec(), + selection.contentCodec(), + JsonCodec.NoMapKeyCodec.class, + selection.valueCodec()); completeResolution(snapshot); return result; } catch (RuntimeException | Error e) { @@ -571,13 +593,31 @@ private JsonTypeInfo resolveTypeInfo(TypeRef declaredType, Object key) { } private JsonTypeInfo resolveTypeInfo(TypeRef declaredType, JsonCodec annotation) { + return resolveTypeInfo( + declaredType, + annotation, + annotation.value(), + annotation.elementCodec(), + annotation.contentCodec(), + annotation.keyCodec(), + annotation.valueCodec()); + } + + /** + * Resolves an occurrence's selected codecs. {@code annotation} is the declaring {@link + * JsonCodec}, or null for a class default, which never selects a child of a composite module + * codec. + */ + private JsonTypeInfo resolveTypeInfo( + TypeRef declaredType, + JsonCodec annotation, + Class> valueCodec, + Class> elementCodec, + Class> contentCodec, + Class keyCodec, + Class> mapValueCodec) { validateCovariant(declaredType); Class rawType = declaredType.getRawType(); - Class> valueCodec = annotation.value(); - Class> elementCodec = annotation.elementCodec(); - Class> contentCodec = annotation.contentCodec(); - Class keyCodec = annotation.keyCodec(); - Class> mapValueCodec = annotation.valueCodec(); boolean hasValue = valueCodec != JsonCodec.NoJsonValueCodec.class; boolean hasElement = elementCodec != JsonCodec.NoJsonValueCodec.class; boolean hasContent = contentCodec != JsonCodec.NoJsonValueCodec.class; @@ -662,7 +702,7 @@ private JsonTypeInfo resolveTypeInfo(TypeRef declaredType, JsonCodec annotati return newTypeInfo(declaredType, codec); } JsonValueCodec codec = sharedRegistry.createCodec(rawType, typeRef, this); - if (codec instanceof CompositeJsonCodec) { + if (codec instanceof CompositeJsonCodec && annotation != null) { JsonTypeInfo typeInfo = newTypeInfo(declaredType, JsonFieldKind.OBJECT, codec, true); ((CompositeJsonCodec) codec).resolveTypes(typeRef, this, annotation); return typeInfo; From 6571da57235b3dafddbdd8ce3ce35abe1a46ecd5 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Sat, 7 Nov 2026 23:44:37 +0100 Subject: [PATCH 23/26] fix(java): read Kotlin Any arguments in codec targets as Object Co-Authored-By: Claude Opus 5.5 --- docs/json/custom-codecs.md | 3 ++- .../fory/json/resolver/JsonDefaultCodecs.java | 7 +++---- .../json/kotlin/KotlinBuiltInCodecsTest.kt | 20 +++++++++++++++++++ 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index 2557598ab4..0d31221dac 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -297,7 +297,8 @@ one class may name at most one codec per target type. A property or creator parameter whose resolved type equals a target uses the codec as if it declared `@JsonCodec(value = ...)`; a primitive property or array element matches its wrapper type. In the declared type of a codec with a Kotlin class on its superclass chain, a `? extends T` that Kotlin emits for declaration-site variance -reads as `T`; a Java codec's target must not contain wildcards. +reads as `T`, including `Any`, which reflection cannot tell from a star projection; a Java +codec's target must not contain wildcards. Otherwise a target equal to the direct child of a Java array, `Collection`, `AtomicReferenceArray`, `Optional`, `AtomicReference`, or the value of a `Map` fills the matching diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index be9721f697..5196409205 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -273,10 +273,9 @@ private Class> childCodec(TypeRef child) { private static Type kotlinInvariant(Type type) { if (type instanceof WildcardType) { WildcardType wildcard = (WildcardType) type; - // An unbounded wildcard reads as ? extends Object and stays a wildcard: it names no type. - if (wildcard.getLowerBounds().length == 0 - && wildcard.getUpperBounds().length == 1 - && wildcard.getUpperBounds()[0] != Object.class) { + // Kotlin writes Any as ? extends Object, which reflection cannot tell from a star + // projection; a star-projected target names no type, so Any is the useful reading. + if (wildcard.getLowerBounds().length == 0 && wildcard.getUpperBounds().length == 1) { return kotlinInvariant(wildcard.getUpperBounds()[0]); } return type; diff --git a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt index 5d3272a0f7..838ea6a90c 100644 --- a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt +++ b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt @@ -177,6 +177,26 @@ class KotlinBuiltInCodecsTest { @JsonDefaultCodec(LongListCodec::class) class LongListHolder(val values: List) + class AnyMapCodec : AbstractJsonValueCodec>() { + override fun write(writer: JsonWriter, value: Map) { + writer.writeString("any:${value.size}") + } + + override fun read(reader: JsonReader): Map { + reader.readString() + return emptyMap() + } + } + + // Kotlin writes Any as ? extends Object; the declaration must still be accepted. + @JsonDefaultCodec(AnyMapCodec::class, TaggedIntCodec::class) + data class AnyTargetDeclared(val count: Int) + + @Test + fun defaultCodecAcceptsKotlinAnyArguments() { + assertEquals("{\"count\":\"i:3\"}", fory.toJson(AnyTargetDeclared(3))) + } + @Test fun defaultCodecMatchesKotlinCollectionTarget() { assertEquals("{\"values\":\"longs:2\"}", fory.toJson(LongListHolder(listOf(1L, 2L)))) From 2da0a9d06b509dc2696b62db45c7ecf1a874b190 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 10 Nov 2026 09:50:07 +0100 Subject: [PATCH 24/26] refactor(java): name the JsonDefaultCodec target type explicitly @JsonDefaultCodec now takes the raw property type and the codec, @JsonDefaultCodec(type = BigDecimal.class, codec = PlainBigDecimalCodec.class), and stays repeatable for several types. The target is no longer inferred from the codec's generic signature, so parameterized targets, Kotlin variance normalization and the codec supertype keep rules are gone. Primitive arrays are no longer filled by a wrapper default. Co-Authored-By: Claude Fable 5.2 --- docs/json/custom-codecs.md | 32 +- .../kotlin/json/corpus/PlatformModels.kt | 19 +- .../json/corpus/KspRetentionResourceTest.kt | 12 - .../processing/JsonTypeProcessor.java | 42 +- .../processing/JsonTypeProcessorTest.java | 59 +-- .../json/annotation/JsonDefaultCodec.java | 50 +-- .../fory/json/resolver/JsonDefaultCodecs.java | 338 +++------------ .../fory/json/ForyJsonGraalVMFeature.java | 23 +- .../fory/json/JsonDefaultCodecTest.java | 386 +++++------------- .../fory/json/kotlin/ksp/KspModelBuilder.kt | 36 +- .../json/kotlin/KotlinBuiltInCodecsTest.kt | 100 +---- 11 files changed, 232 insertions(+), 865 deletions(-) diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index 0d31221dac..efebe0ea19 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -278,7 +278,7 @@ import java.util.List; import java.util.Optional; import org.apache.fory.json.annotation.JsonDefaultCodec; -@JsonDefaultCodec(PlainDecimalCodec.class) +@JsonDefaultCodec(type = BigDecimal.class, codec = PlainDecimalCodec.class) public class Invoice { public BigDecimal total; // PlainDecimalCodec public Optional discount; // contentCodec = PlainDecimalCodec @@ -288,23 +288,19 @@ public class Invoice { } ``` -Each codec targets the type argument it declares for `JsonValueCodec`. `PlainDecimalCodec extends -AbstractJsonValueCodec` targets `BigDecimal`, and a codec declared over -`Optional` targets exactly that parameterized type. The target must be concrete. List -several codecs in one annotation, `@JsonDefaultCodec({A.class, B.class})`, or repeat the annotation; -one class may name at most one codec per target type. +`type` names the raw property type and `codec` the codec used for it. Repeat the annotation for +several types; one class may name each type at most once, and a primitive and its wrapper are the +same type. Type arguments are not part of the match, so `type = List.class` covers every `List` +property; use a property `JsonCodec` where one parameterization needs its own codec. -A property or creator parameter whose resolved type equals a target uses the codec as if it -declared `@JsonCodec(value = ...)`; a primitive property or array element matches its wrapper type. -In the declared type of a codec with a Kotlin class on its superclass chain, a `? extends T` that Kotlin emits for declaration-site variance -reads as `T`, including `Any`, which reflection cannot tell from a star projection; a Java -codec's target must not contain wildcards. +A property or creator parameter whose raw type equals `type` uses the codec as if it declared +`@JsonCodec(value = ...)`. -Otherwise a target equal to the direct child of a Java array, `Collection`, +Otherwise a `type` equal to the direct child of an object array, `Collection`, `AtomicReferenceArray`, `Optional`, `AtomicReference`, or the value of a `Map` fills the matching child member from the table above; a language module's own containers, such as Scala `Option` or -`Seq`, are not filled, so a `Byte` default writes a `byte[]` as a JSON array of codec values whatever -`byteArrayFormat` says. A child is filled only where the container keeps its standard mapping: a +`Seq`, are not filled, and neither are primitive arrays, so a `Byte` default leaves `byte[]` to +`byteArrayFormat`. A child is filled only where the container keeps its standard mapping: a registered codec or factory, a module, or a type declaration that owns the container keeps it unchanged. Deeper nesting is not searched, and a wildcard child such as `List` keeps its mapping, as an explicit child member would reject it. @@ -315,12 +311,12 @@ described above for every property it reaches. Properties that declare `JsonCode there is no separate per-property opt-out. A value-class property read and written through its unboxed carrier cannot take a codec, so a default that matches one fails like a declared `JsonCodec`; a nullable or container occurrence of -the value class is boxed and uses the default. A target that is a Kotlin unsigned type, which the +the value class is boxed and uses the default. A `type` that is a Kotlin unsigned type, which the Kotlin module carries as a tagged primitive, is rejected. -Defaults declared on superclasses apply to the subclass, and a subclass default for the same target -type replaces the inherited one. Defaults stop at the class boundary: a nested object type uses its -own declarations. A declaration on an interface is rejected; the build-time processors also reject +Defaults declared on superclasses apply to the subclass, and a subclass default for the same type +replaces the inherited one. Defaults stop at the class boundary: a nested object type uses its own +declarations. A declaration on an interface is rejected; the build-time processors also reject one on an enum or annotation type, which never gets an object mapping. An exact-target Mixin may supply or replace the annotation; a Mixin that supplies or removes either the single or the repeated form replaces both forms declared on the target, and a removal also drops the defaults diff --git a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt index 2a3359592d..a748308530 100644 --- a/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt +++ b/integration_tests/kotlin_json_corpus/src/main/kotlin/org/apache/fory/integration/kotlin/json/corpus/PlatformModels.kt @@ -95,9 +95,7 @@ public class PlatformTokenCodec : AbstractJsonValueCodec() { } } -public abstract class PlatformPrefixCodec : AbstractJsonValueCodec() - -public class PlatformDefaultTokenCodec : PlatformPrefixCodec() { +public class PlatformDefaultTokenCodec : AbstractJsonValueCodec() { override fun write(writer: JsonWriter, value: PlatformToken?) { if (value == null) writer.writeNull() else writer.writeString("t:" + value.value) } @@ -109,25 +107,28 @@ public class PlatformDefaultTokenCodec : PlatformPrefixCodec() { } @JsonType -@JsonDefaultCodec(PlatformDefaultTokenCodec::class) +@JsonDefaultCodec(type = PlatformToken::class, codec = PlatformDefaultTokenCodec::class) public data class PlatformDefaultCodecs( public val token: PlatformToken, public val tokens: List, ) -@JsonDefaultCodec(PlatformDefaultTokenCodec::class) public abstract class PlatformDefaultBase +@JsonDefaultCodec(type = PlatformToken::class, codec = PlatformDefaultTokenCodec::class) +public abstract class PlatformDefaultBase @JsonType public data class PlatformInheritedDefaults(public val token: PlatformToken) : PlatformDefaultBase() @JsonType -@JsonDefaultCodec.List(JsonDefaultCodec(PlatformDefaultTokenCodec::class)) +@JsonDefaultCodec.List( + JsonDefaultCodec(type = PlatformToken::class, codec = PlatformDefaultTokenCodec::class) +) public data class PlatformContainerDefaults(public val token: PlatformToken) public data class PlatformLabel(public val value: String) -public class PlatformLabelCodec : PlatformPrefixCodec() { +public class PlatformLabelCodec : AbstractJsonValueCodec() { override fun write(writer: JsonWriter, value: PlatformLabel?) { if (value == null) writer.writeNull() else writer.writeString("l:" + value.value) } @@ -144,8 +145,8 @@ public data class PlatformMixinDefaultsTarget( ) @JsonMixin(target = PlatformMixinDefaultsTarget::class) -@JsonDefaultCodec(PlatformDefaultTokenCodec::class) -@JsonDefaultCodec(PlatformLabelCodec::class) +@JsonDefaultCodec(type = PlatformToken::class, codec = PlatformDefaultTokenCodec::class) +@JsonDefaultCodec(type = PlatformLabel::class, codec = PlatformLabelCodec::class) public interface PlatformMixinDefaults @JsonSubTypes diff --git a/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt b/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt index 3273d54663..41a6dc7ea3 100644 --- a/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt +++ b/integration_tests/kotlin_json_corpus/src/test/kotlin/org/apache/fory/integration/kotlin/json/corpus/KspRetentionResourceTest.kt @@ -103,10 +103,6 @@ public class KspRetentionResourceTest { ) val defaultCodecs = rules("PlatformDefaultCodecs") assertConstructor(defaultCodecs, "$PACKAGE.PlatformDefaultTokenCodec") - assertTrue( - defaultCodecs.contains("-keep,allowoptimization class $PACKAGE.PlatformPrefixCodec\n"), - defaultCodecs, - ) assertTrue( defaultCodecs.contains("@interface org.apache.fory.json.annotation.JsonDefaultCodec\n"), defaultCodecs, @@ -118,10 +114,6 @@ public class KspRetentionResourceTest { for (model in listOf("PlatformInheritedDefaults", "PlatformContainerDefaults")) { val text = rules(model) assertConstructor(text, "$PACKAGE.PlatformDefaultTokenCodec") - assertTrue( - text.contains("-keep,allowoptimization class $PACKAGE.PlatformPrefixCodec\n"), - text, - ) assertTrue( text.contains("@interface org.apache.fory.json.annotation.JsonDefaultCodec\$List"), text, @@ -135,10 +127,6 @@ public class KspRetentionResourceTest { val mixinDefaults = mixinRules("PlatformMixinDefaults") assertConstructor(mixinDefaults, "$PACKAGE.PlatformDefaultTokenCodec") assertConstructor(mixinDefaults, "$PACKAGE.PlatformLabelCodec") - assertTrue( - mixinDefaults.contains("-keep,allowoptimization class $PACKAGE.PlatformPrefixCodec\n"), - mixinDefaults, - ) val mixin = mixinRules("PlatformJavaProfileMixin") assertTrue(mixin.contains("class $PACKAGE.PlatformJavaProfile"), mixin) assertTrue(mixin.contains("class $PACKAGE.PlatformJavaProfileMixin"), mixin) diff --git a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java index 70addccdef..fb1e189bee 100644 --- a/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java +++ b/java/fory-annotation-processor/src/main/java/org/apache/fory/annotation/processing/JsonTypeProcessor.java @@ -642,37 +642,12 @@ private void collectDefaultCodecs(AnnotationMirror annotation, Model model) { if (annotation == null) { return; } - AnnotationValue value = annotationValue(annotation, "value"); - if (value == null || !(value.getValue() instanceof List)) { - return; - } - for (Object entry : (List) value.getValue()) { - Object codecType = - entry instanceof AnnotationValue ? ((AnnotationValue) entry).getValue() : null; - TypeElement codec = - codecType instanceof TypeMirror ? asTypeElement((TypeMirror) codecType) : null; - if (codec != null) { - model.codecTypes.add(elements.getBinaryName(codec).toString()); - collectCodecSupertypes(codec, model); - } - } - } - - /** - * The runtime reads a default codec's target from the generic signatures of its supertypes, so a - * shrinker must neither drop nor merge the classes on the way to {@code JsonValueCodec}. - */ - private void collectCodecSupertypes(TypeElement type, Model model) { - List supertypes = new ArrayList<>(type.getInterfaces()); - supertypes.add(type.getSuperclass()); - for (TypeMirror supertype : supertypes) { - TypeElement element = asTypeElement(supertype); - if (element == null || element.getQualifiedName().toString().startsWith("java.")) { - continue; - } - if (model.codecSupertypes.add(elements.getBinaryName(element).toString())) { - collectCodecSupertypes(element, model); - } + AnnotationValue value = annotationValue(annotation, "codec"); + Object codecType = value == null ? null : value.getValue(); + TypeElement codec = + codecType instanceof TypeMirror ? asTypeElement((TypeMirror) codecType) : null; + if (codec != null) { + model.codecTypes.add(elements.getBinaryName(codec).toString()); } } @@ -774,9 +749,6 @@ private String writeR8(Model model) { : elements.getBinaryName(annotationElement).toString()) .append("\n"); } - for (String supertype : model.codecSupertypes) { - builder.append("-keep,allowoptimization class ").append(supertype).append("\n"); - } for (String container : model.containerTypes) { builder .append("-keep,allowoptimization,allowobfuscation class ") @@ -1507,7 +1479,6 @@ private static final class Model { final Set annotationTypes = new LinkedHashSet<>(); final Set containerTypes = new LinkedHashSet<>(); final Set codecTypes = new LinkedHashSet<>(); - final Set codecSupertypes = new LinkedHashSet<>(); final Set binaryFallbackTypes = new LinkedHashSet<>(); final Set annotationOwnerTypes = new LinkedHashSet<>(); final Set nameTypes = new LinkedHashSet<>(); @@ -1563,7 +1534,6 @@ void merge(Model other) { annotationTypes.addAll(other.annotationTypes); containerTypes.addAll(other.containerTypes); codecTypes.addAll(other.codecTypes); - codecSupertypes.addAll(other.codecSupertypes); binaryFallbackTypes.addAll(other.binaryFallbackTypes); annotationOwnerTypes.addAll(other.annotationOwnerTypes); nameTypes.addAll(other.nameTypes); diff --git a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java index 739c3c9c59..383f2989f3 100644 --- a/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java +++ b/java/fory-annotation-processor/src/test/java/org/apache/fory/annotation/processing/JsonTypeProcessorTest.java @@ -127,7 +127,7 @@ public void defaultCodecOnInterfaceFailsCompilation() throws Exception { "test.DefaultContract", "package test;\n" + "import org.apache.fory.json.annotation.JsonDefaultCodec;\n" - + "@JsonDefaultCodec(DefaultContract.LongCodec.class)\n" + + "@JsonDefaultCodec(type = Long.class, codec = DefaultContract.LongCodec.class)\n" + "public interface DefaultContract {\n" + " final class LongCodec extends org.apache.fory.json.codec.AbstractJsonValueCodec {\n" + " public void write(org.apache.fory.json.writer.JsonWriter writer, Long value) {}\n" @@ -147,7 +147,7 @@ public void defaultCodecOnEnumFailsCompilation() throws Exception { "test.DefaultStatus", "package test;\n" + "import org.apache.fory.json.annotation.JsonDefaultCodec;\n" - + "@JsonDefaultCodec(DefaultStatus.LongCodec.class)\n" + + "@JsonDefaultCodec(type = Long.class, codec = DefaultStatus.LongCodec.class)\n" + "public enum DefaultStatus {\n" + " ACTIVE;\n" + " public static final class LongCodec\n" @@ -173,9 +173,9 @@ public void mixinDefaultCodecRules() throws Exception { + " public Long id;\n" + "}\n" + "@JsonMixin(target = DefaultTarget.class)\n" - + "@JsonDefaultCodec(DefaultMixin.LongCodec.class) interface DefaultMixin {\n" - + " abstract class Prefix extends org.apache.fory.json.codec.AbstractJsonValueCodec {}\n" - + " final class LongCodec extends Prefix {\n" + + "@JsonDefaultCodec(type = Long.class, codec = DefaultMixin.LongCodec.class)\n" + + "interface DefaultMixin {\n" + + " final class LongCodec extends org.apache.fory.json.codec.AbstractJsonValueCodec {\n" + " public void write(org.apache.fory.json.writer.JsonWriter writer, Long value) {}\n" + " public Long read(org.apache.fory.json.reader.JsonReader reader) { return null; }\n" + " }\n" @@ -183,7 +183,6 @@ public void mixinDefaultCodecRules() throws Exception { assertTrue(result.success, result.diagnostics()); String rules = result.generatedResource(MIXIN_RULE_PREFIX + "test.DefaultMixin.pro"); assertTrue(rules.contains("class test.DefaultMixin$LongCodec { public (); }"), rules); - assertTrue(rules.contains("-keep,allowoptimization class test.DefaultMixin$Prefix\n"), rules); } @Test @@ -1695,7 +1694,8 @@ public void defaultCodecRecordPipeline() throws Exception { + "import java.math.BigDecimal;\n" + "import java.util.Optional;\n" + "import org.apache.fory.json.annotation.*;\n" - + "@JsonType @JsonDefaultCodec(DefaultCodecRecord.Plain.class)\n" + + "@JsonType\n" + + "@JsonDefaultCodec(type = BigDecimal.class, codec = DefaultCodecRecord.Plain.class)\n" + "public record DefaultCodecRecord(BigDecimal price, Optional bid) {\n" + " public DefaultCodecRecord {\n" + " bid = bid == null ? Optional.empty() : bid;\n" @@ -1737,14 +1737,9 @@ public void defaultCodecRules() throws Exception { "test.DefaultCodecBase", "package test;\n" + "import org.apache.fory.json.annotation.JsonDefaultCodec;\n" - + "@JsonDefaultCodec(DefaultCodecBase.BaseCodec.class)\n" + + "@JsonDefaultCodec(type = Long.class, codec = DefaultCodecBase.BaseCodec.class)\n" + "public class DefaultCodecBase {\n" - + " public abstract static class Prefix\n" - + " extends org.apache.fory.json.codec.AbstractJsonValueCodec {}\n" - + " public static final class BaseCodec extends Prefix {\n" - + " public void write(org.apache.fory.json.writer.JsonWriter writer, Long value) {}\n" - + " public Long read(org.apache.fory.json.reader.JsonReader reader) { return null; }\n" - + " }\n" + + String.format(codec, "BaseCodec", "Long", "Long", "Long") + " public Long id;\n" + "}\n"); sources.put( @@ -1755,8 +1750,8 @@ public void defaultCodecRules() throws Exception { + "import org.apache.fory.json.annotation.JsonDefaultCodec;\n" + "import org.apache.fory.json.annotation.JsonType;\n" + "@JsonType\n" - + "@JsonDefaultCodec(DefaultCodecModel.DecimalCodec.class)\n" - + "@JsonDefaultCodec(DefaultCodecModel.OptionalCodec.class)\n" + + "@JsonDefaultCodec(type = BigDecimal.class, codec = DefaultCodecModel.DecimalCodec.class)\n" + + "@JsonDefaultCodec(type = Optional.class, codec = DefaultCodecModel.OptionalCodec.class)\n" + "public class DefaultCodecModel extends DefaultCodecBase {\n" + String.format(codec, "DecimalCodec", "BigDecimal", "BigDecimal", "BigDecimal") + String.format( @@ -1776,13 +1771,6 @@ public void defaultCodecRules() throws Exception { assertTrue( rules.contains("class test.DefaultCodecModel$OptionalCodec { public (); }"), rules); assertTrue(rules.contains("class test.DefaultCodecBase$BaseCodec { public (); }"), rules); - // The codec's target is read from the generic signature of its intermediate superclass. - assertTrue( - rules.contains("-keep,allowoptimization class test.DefaultCodecBase$Prefix\n"), rules); - assertTrue( - rules.contains( - "-keep,allowoptimization class org.apache.fory.json.codec.AbstractJsonValueCodec\n"), - rules); // The model itself uses only the repeated form, compiled into the nested container. String keep = "-keep,allowoptimization,allowobfuscation @interface "; assertTrue(rules.contains(keep + "org.apache.fory.json.annotation.JsonDefaultCodec\n"), rules); @@ -2194,31 +2182,6 @@ public void subtypeRules() throws Exception { assertTrue(rules.contains("-keep,allowoptimization class external.HiddenChild"), rules); } - @Test - public void defaultCodecSupertypesMergeFromSubtypeModels() throws Exception { - assumeJava17Source(); - CompilationResult result = - compile( - "test.Priced", - "package test;\n" - + "import org.apache.fory.json.annotation.JsonDefaultCodec;\n" - + "import org.apache.fory.json.annotation.JsonSubTypes;\n" - + "@JsonSubTypes(property = \"kind\")\n" - + "public sealed interface Priced permits Priced.Item {\n" - + " abstract class Prefix extends org.apache.fory.json.codec.AbstractJsonValueCodec {}\n" - + " final class LongCodec extends Prefix {\n" - + " public void write(org.apache.fory.json.writer.JsonWriter writer, Long value) {}\n" - + " public Long read(org.apache.fory.json.reader.JsonReader reader) { return null; }\n" - + " }\n" - + " @JsonDefaultCodec(LongCodec.class)\n" - + " final class Item implements Priced { public Long price; public Item() {} }\n" - + "}\n"); - assertTrue(result.success, result.diagnostics()); - String rules = result.generatedResource(RULE_PREFIX + "test.Priced.pro"); - assertTrue(rules.contains("class test.Priced$LongCodec { public (); }"), rules); - assertTrue(rules.contains("-keep,allowoptimization class test.Priced$Prefix\n"), rules); - } - @Test public void inferredSubtypeTable() throws Exception { assumeJava17Source(); diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java index 3194ddbe82..5c1777df59 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java @@ -28,34 +28,31 @@ import org.apache.fory.json.codec.JsonValueCodec; /** - * Selects default codecs for the properties of the annotated class by their declared type. + * Selects a default codec for the properties of the annotated class that have one declared type. + * Repeat the annotation for several types; one class may name each type at most once. * - *

Codecs may be listed in one annotation, {@code @JsonDefaultCodec({A.class, B.class})}, or in - * repeated annotations, {@code @JsonDefaultCodec(A.class) @JsonDefaultCodec(B.class)}. + *

{@code
+ * @JsonDefaultCodec(type = BigDecimal.class, codec = PlainBigDecimalCodec.class)
+ * public class Invoice { ... }
+ * }
* - *

Each codec targets the type argument it declares for {@link JsonValueCodec}: a codec of {@code - * BigDecimal} targets {@code BigDecimal}, a codec of {@code Optional} targets exactly - * {@code Optional}. That type must be concrete, without type variables or wildcards, - * except that in a Kotlin codec a covariant {@code ? extends T}, which Kotlin emits, reads as - * {@code T}. One class may name at most one codec per target type. - * - *

A property or creator parameter whose resolved type equals a target uses that codec as if it - * declared {@code @JsonCodec(value = ...)}; a primitive property or array element matches its - * wrapper type. Without a whole-type match, a target that equals the direct child of an array, - * {@code Collection}, {@code AtomicReferenceArray}, {@code Optional}, {@code AtomicReference}, or - * the value of a {@code Map} (Java containers only) is used as the matching {@link JsonCodec} child - * member, but only where the container keeps its standard mapping: a registered codec or factory, a - * module, or a type declaration that owns the container keeps it unchanged. + *

A property or creator parameter whose raw type equals {@link #type()} uses the codec as if it + * declared {@code @JsonCodec(value = ...)}; a primitive and its wrapper are the same type. + * Otherwise a {@link #type()} that equals the direct child of an object array, {@code Collection}, + * {@code AtomicReferenceArray}, {@code Optional}, {@code AtomicReference}, or the value of a {@code + * Map} (Java containers only) is used as the matching {@link JsonCodec} child member, but only + * where the container keeps its standard mapping: a registered codec or factory, a module, or a + * type declaration that owns the container keeps it unchanged. Primitive arrays are not filled. * *

A property that declares its own {@link JsonCodec}, {@link JsonFormat}, {@link JsonByteArray}, * {@link JsonRawValue}, or {@link JsonUnwrapped}, and JSON Any properties, do not use defaults. - * Defaults declared on superclasses apply too, and a subclass default for the same target type - * replaces the inherited one. A default codec receives and owns null like a property {@link - * JsonCodec}. Declarations on interfaces and Kotlin unsigned targets are rejected. Defaults do not - * reach nested object types, which use their own class declarations. A value-class property read - * and written through its unboxed carrier cannot take a codec, so a default that matches one fails - * like a declared {@link JsonCodec}; a nullable or container occurrence of the value class is boxed - * and uses the default. An exact-target {@link JsonMixin} may supply or replace this annotation; + * Defaults declared on superclasses apply too, and a subclass default for the same type replaces + * the inherited one. A default codec receives and owns null like a property {@link JsonCodec}. + * Declarations on interfaces and Kotlin unsigned types are rejected. Defaults do not reach nested + * object types, which use their own class declarations. A value-class property read and written + * through its unboxed carrier cannot take a codec, so a default that matches one fails like a + * declared {@link JsonCodec}; a nullable or container occurrence of the value class is boxed and + * uses the default. An exact-target {@link JsonMixin} may supply or replace this annotation; * supplying or removing either the single or the repeated form replaces both forms declared on the * target, and a removal also drops inherited defaults. */ @@ -64,8 +61,11 @@ @Target(ElementType.TYPE) @Repeatable(JsonDefaultCodec.List.class) public @interface JsonDefaultCodec { - /** Returns the default codecs; each targets its declared value type. */ - Class>[] value(); + /** Returns the raw property type the codec applies to. */ + Class type(); + + /** Returns the codec used for properties of {@link #type()}. */ + Class> codec(); /** Container of repeated {@link JsonDefaultCodec} declarations on one class. */ @Documented diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 5196409205..0a84c26544 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -19,17 +19,12 @@ package org.apache.fory.json.resolver; -import java.lang.annotation.Annotation; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceArray; @@ -40,6 +35,7 @@ import org.apache.fory.json.codec.CodecUtils; import org.apache.fory.json.codec.JsonValueCodec; import org.apache.fory.reflect.TypeRef; +import org.apache.fory.type.TypeUtils; import org.apache.fory.type.Types; /** @@ -51,6 +47,7 @@ @Internal public final class JsonDefaultCodecs { private static final JsonDefaultCodecs NONE = new JsonDefaultCodecs(new Entry[0]); + // The Kotlin module carries these as tagged JVM primitives, so no occurrence could match. private static final List KOTLIN_UNSIGNED = Arrays.asList( "kotlin.UByte", @@ -104,17 +101,15 @@ public static JsonDefaultCodecs of(Class type, JsonSharedRegistry registry) { } List declared = new ArrayList<>(); for (JsonDefaultCodec annotation : annotations) { - for (Class> codecClass : annotation.value()) { - Entry entry = new Entry(targetType(declaring, codecClass), codecClass); - if (find(declared, entry.target) != null) { - throw new ForyJsonException( - "Duplicate @JsonDefaultCodec target " - + entry.target.getTypeName() - + " on " - + declaring.getName()); - } - declared.add(entry); + Entry entry = entry(declaring, annotation); + if (find(declared, entry.target) != null) { + throw new ForyJsonException( + "Duplicate @JsonDefaultCodec type " + + entry.target.getName() + + " on " + + declaring.getName()); } + declared.add(entry); } if (entries == null) { entries = declared; @@ -145,25 +140,49 @@ private static void rejectInterfaceDeclarations( } } + private static Entry entry(Class declaring, JsonDefaultCodec annotation) { + Class target = annotation.type(); + if (target == void.class + || KOTLIN_UNSIGNED.contains(target.getName()) + || annotation.codec() == JsonCodec.NoJsonValueCodec.class) { + throw new ForyJsonException( + "Invalid @JsonDefaultCodec on " + + declaring.getName() + + ": type " + + target.getName() + + " with codec " + + annotation.codec().getName()); + } + // A primitive and its wrapper are one target. + return new Entry(TypeUtils.wrap(target), annotation.codec()); + } + + private static Entry find(List entries, Class target) { + for (Entry entry : entries) { + if (entry.target == target) { + return entry; + } + } + return null; + } + public boolean isEmpty() { return entries.length == 0; } /** Returns the codecs a property of {@code type} defaults to, or null without a match. */ public Selection select(TypeRef type) { - if (entries.length == 0) { + if (entries.length == 0 || semantic(type)) { return null; } Class> codec = codec(type); if (codec != null) { return new Selection(codec, null, null, null); } - if (semantic(type)) { - return null; - } Class rawType = type.getRawType(); if (rawType.isArray()) { - codec = childCodec(type.getComponentType()); + // A primitive array keeps its own mapping, such as byteArrayFormat for byte[]. + codec = rawType.getComponentType().isPrimitive() ? null : childCodec(type.getComponentType()); return codec == null ? null : new Selection(null, codec, null, null); } if (rawType.getTypeParameters().length != 0 && !type.hasExplicitTypeArguments()) { @@ -184,18 +203,11 @@ public Selection select(TypeRef type) { return null; } - /** - * Returns the default for one occurrence. A primitive matches its wrapper, but a type a language - * module tags with its own semantic type, such as a Kotlin {@code UInt} carried as {@code int}, - * keeps that module's mapping. - */ + /** Returns the default whose type is the raw type of this occurrence, or null. */ private Class> codec(TypeRef type) { - if (semantic(type)) { - return null; - } - TypeRef occurrence = type.isPrimitive() ? type.wrap() : type; + Class rawType = TypeUtils.wrap(type.getRawType()); for (Entry entry : entries) { - if (matches(entry.target, occurrence)) { + if (entry.target == rawType) { return entry.codecClass; } } @@ -203,277 +215,23 @@ private Class> codec(TypeRef type) { } /** - * Matches a target against an occurrence through the occurrence's own tokens. A language module - * may describe a generic array, at any depth, as a raw array class with a parameterized component - * token, so arrays are compared by component and parameterized types argument by argument. - */ - private static boolean matches(Type target, TypeRef occurrence) { - Type type = occurrence.getType(); - if (type instanceof WildcardType) { - return sameType(target, type); - } - if (occurrence.getRawType().isArray()) { - // Compare by component for raw and generic array targets alike: an occurrence token may - // carry a parameterized component that its raw array class does not show. - if (target instanceof GenericArrayType) { - return matches( - ((GenericArrayType) target).getGenericComponentType(), occurrence.getComponentType()); - } - if (target instanceof Class && ((Class) target).isArray()) { - return matches(((Class) target).getComponentType(), occurrence.getComponentType()); - } - } - if (target instanceof ParameterizedType && type instanceof ParameterizedType) { - ParameterizedType parameterized = (ParameterizedType) target; - ParameterizedType declared = (ParameterizedType) type; - Type[] arguments = parameterized.getActualTypeArguments(); - Type[] declaredArguments = declared.getActualTypeArguments(); - if (!parameterized.getRawType().equals(declared.getRawType()) - || arguments.length != declaredArguments.length) { - return false; - } - List> tokens = occurrence.getTypeArguments(); - for (int i = 0; i < arguments.length; i++) { - if (!matches(arguments[i], argument(declaredArguments[i], tokens, i, arguments.length))) { - return false; - } - } - Type owner = parameterized.getOwnerType(); - return owner == null || sameType(owner, declared.getOwnerType()); - } - return sameType(target, type); - } - - /** - * Returns the occurrence token of one declared type argument. {@code TypeRef} may normalize a - * container subclass's arguments to its element type, so a token is used only when its reflected - * type is the declared argument itself; it then adds what reflection lacks, such as a Kotlin - * array's parameterized component token. + * A wildcard child is not concrete, which an explicit child member rejects as well, and a child a + * language module tags with its own semantic type keeps that module's mapping. */ - private static TypeRef argument(Type declared, List> tokens, int index, int count) { - if (tokens.size() == count) { - TypeRef token = tokens.get(index); - if (sameType(declared, token.getType())) { - return token; - } - } - return TypeRef.of(declared); - } - - /** A wildcard child is not concrete, which an explicit child member rejects as well. */ private Class> childCodec(TypeRef child) { - return child.getType() instanceof WildcardType ? null : codec(child); - } - - /** - * Reads each covariant {@code ? extends T} in a Kotlin codec's declared type as {@code T}. Kotlin - * writes declaration-site variance into generic signatures, so a Kotlin codec of {@code - * List} declares {@code List}; a Java codec's wildcards stay wildcards. - */ - private static Type kotlinInvariant(Type type) { - if (type instanceof WildcardType) { - WildcardType wildcard = (WildcardType) type; - // Kotlin writes Any as ? extends Object, which reflection cannot tell from a star - // projection; a star-projected target names no type, so Any is the useful reading. - if (wildcard.getLowerBounds().length == 0 && wildcard.getUpperBounds().length == 1) { - return kotlinInvariant(wildcard.getUpperBounds()[0]); - } - return type; - } - if (type instanceof ParameterizedType) { - ParameterizedType parameterized = (ParameterizedType) type; - Type[] arguments = parameterized.getActualTypeArguments().clone(); - for (int i = 0; i < arguments.length; i++) { - arguments[i] = kotlinInvariant(arguments[i]); - } - Type owner = parameterized.getOwnerType(); - return new InvariantParameterizedType( - parameterized.getRawType(), arguments, owner == null ? null : kotlinInvariant(owner)); - } - if (type instanceof GenericArrayType) { - Type component = kotlinInvariant(((GenericArrayType) type).getGenericComponentType()); - return component instanceof Class - ? java.lang.reflect.Array.newInstance((Class) component, 0).getClass() - : new InvariantArrayType(component); - } - return type; - } - - /** - * Returns whether any class on the codec's superclass chain is Kotlin. The target is resolved - * through that whole chain, so a Kotlin base class can contribute the variance wildcards. - */ - private static boolean kotlinCodec(Class codecClass) { - for (Class type = codecClass; type != null; type = type.getSuperclass()) { - for (Annotation annotation : type.getDeclaredAnnotations()) { - if (annotation.annotationType().getName().equals("kotlin.Metadata")) { - return true; - } - } - } - return false; + return child.getType() instanceof WildcardType || semantic(child) ? null : codec(child); } + /** A type such as a Kotlin {@code UInt} carried as {@code int} keeps its module's mapping. */ private static boolean semantic(TypeRef type) { return type.getTypeExtMeta() != null && type.getTypeExtMeta().typeId() != Types.UNKNOWN; } - private static Entry find(List entries, Type target) { - for (Entry entry : entries) { - if (sameType(entry.target, target)) { - return entry; - } - } - return null; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - private static Type targetType( - Class declaring, Class> codecClass) { - if (codecClass == JsonCodec.NoJsonValueCodec.class) { - throw invalid(declaring, codecClass, "is not a codec"); - } - List> arguments = - ((TypeRef) TypeRef.of(codecClass)).getSupertype(JsonValueCodec.class).getTypeArguments(); - Type target = arguments.size() == 1 ? arguments.get(0).getType() : null; - if (target != null && kotlinCodec(codecClass)) { - target = kotlinInvariant(target); - } - if (target == null || !concrete(target)) { - throw invalid(declaring, codecClass, "does not declare a concrete value type"); - } - if (target instanceof Class && KOTLIN_UNSIGNED.contains(((Class) target).getName())) { - // The Kotlin module carries these as tagged JVM primitives, so no occurrence could match. - throw invalid(declaring, codecClass, "cannot target the Kotlin unsigned type " + target); - } - return target; - } - - private static boolean concrete(Type type) { - if (type instanceof Class) { - return true; - } - if (type instanceof ParameterizedType) { - ParameterizedType parameterized = (ParameterizedType) type; - if (!(parameterized.getRawType() instanceof Class)) { - return false; - } - for (Type argument : parameterized.getActualTypeArguments()) { - if (!concrete(argument)) { - return false; - } - } - return parameterized.getOwnerType() == null || concrete(parameterized.getOwnerType()); - } - if (type instanceof GenericArrayType) { - return concrete(((GenericArrayType) type).getGenericComponentType()); - } - return false; - } - - /** Compares reflected types structurally, independent of their implementation classes. */ - private static boolean sameType(Type a, Type b) { - if (a instanceof Class || b instanceof Class) { - return a.equals(b); - } - if (a instanceof ParameterizedType && b instanceof ParameterizedType) { - ParameterizedType left = (ParameterizedType) a; - ParameterizedType right = (ParameterizedType) b; - Type[] leftArguments = left.getActualTypeArguments(); - Type[] rightArguments = right.getActualTypeArguments(); - if (!left.getRawType().equals(right.getRawType()) - || leftArguments.length != rightArguments.length) { - return false; - } - for (int i = 0; i < leftArguments.length; i++) { - if (!sameType(leftArguments[i], rightArguments[i])) { - return false; - } - } - Type leftOwner = left.getOwnerType(); - Type rightOwner = right.getOwnerType(); - return leftOwner == null || rightOwner == null - ? Objects.equals(leftOwner, rightOwner) - : sameType(leftOwner, rightOwner); - } - if (a instanceof GenericArrayType && b instanceof GenericArrayType) { - return sameType( - ((GenericArrayType) a).getGenericComponentType(), - ((GenericArrayType) b).getGenericComponentType()); - } - return a.equals(b); - } - - private static ForyJsonException invalid(Class declaring, Class codecClass, String reason) { - return new ForyJsonException( - "Invalid @JsonDefaultCodec on " - + declaring.getName() - + ": " - + codecClass.getName() - + " " - + reason); - } - - /** A Kotlin codec target with its covariant wildcards read as their bounds. */ - private static final class InvariantParameterizedType implements ParameterizedType { - private final Type rawType; - private final Type[] arguments; - private final Type ownerType; - - private InvariantParameterizedType(Type rawType, Type[] arguments, Type ownerType) { - this.rawType = rawType; - this.arguments = arguments; - this.ownerType = ownerType; - } - - @Override - public Type[] getActualTypeArguments() { - return arguments.clone(); - } - - @Override - public Type getRawType() { - return rawType; - } - - @Override - public Type getOwnerType() { - return ownerType; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(rawType.getTypeName()).append('<'); - for (int i = 0; i < arguments.length; i++) { - builder.append(i == 0 ? "" : ", ").append(arguments[i].getTypeName()); - } - return builder.append('>').toString(); - } - } - - private static final class InvariantArrayType implements GenericArrayType { - private final Type component; - - private InvariantArrayType(Type component) { - this.component = component; - } - - @Override - public Type getGenericComponentType() { - return component; - } - - @Override - public String toString() { - return component.getTypeName() + "[]"; - } - } - private static final class Entry { - private final Type target; + private final Class target; private final Class> codecClass; - private Entry(Type target, Class> codecClass) { + private Entry(Class target, Class> codecClass) { this.target = target; this.codecClass = codecClass; } diff --git a/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java b/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java index 01771c29f4..880f4842a5 100644 --- a/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java +++ b/java/fory-json/src/main/java17/org/apache/fory/json/ForyJsonGraalVMFeature.java @@ -117,7 +117,6 @@ final class ForyJsonGraalVMFeature implements Feature { private final Set> scalaFactoryModels = ConcurrentHashMap.newKeySet(); private final Set> scalaEnumerationOwners = ConcurrentHashMap.newKeySet(); private final Set> processedCodecs = ConcurrentHashMap.newKeySet(); - private final Set> processedCodecSupertypes = ConcurrentHashMap.newKeySet(); private final Set> processedContainers = ConcurrentHashMap.newKeySet(); private final Set processedCreators = new LinkedHashSet<>(); // Reflection-only registrations are tracked apart from processedCreators, whose membership also @@ -1114,26 +1113,8 @@ private void registerCodecs(JsonCodec annotation) { } private void registerDefaultCodecs(JsonDefaultCodec annotation) { - if (annotation == null) { - return; - } - for (Class codecClass : annotation.value()) { - registerCodec(codecClass); - registerCodecSupertypes(codecClass); - } - } - - /** The runtime reads a default codec's target from the generic signatures of its supertypes. */ - private void registerCodecSupertypes(Class type) { - List> supertypes = new ArrayList<>(Arrays.asList(type.getInterfaces())); - if (type.getSuperclass() != null) { - supertypes.add(type.getSuperclass()); - } - for (Class supertype : supertypes) { - if (supertype != Object.class && processedCodecSupertypes.add(supertype)) { - RuntimeReflection.register(supertype); - registerCodecSupertypes(supertype); - } + if (annotation != null) { + registerCodec(annotation.codec()); } } diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index 9aea52d8a1..d55eb26f71 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -83,15 +83,15 @@ public BigDecimal read(JsonReader reader) { } } - public static final class TaggedOptionalCodec - extends AbstractJsonValueCodec> { + @SuppressWarnings("rawtypes") + public static final class TaggedOptionalCodec extends AbstractJsonValueCodec { @Override - public void write(JsonWriter writer, Optional value) { - writer.writeString("od:" + value.get().toPlainString()); + public void write(JsonWriter writer, Optional value) { + writer.writeString("od:" + ((BigDecimal) value.get()).toPlainString()); } @Override - public Optional read(JsonReader reader) { + public Optional read(JsonReader reader) { return Optional.of(new BigDecimal(reader.readString().substring(3))); } } @@ -108,19 +108,7 @@ public Integer read(JsonReader reader) { } } - public static final class WildcardListCodec extends AbstractJsonValueCodec> { - @Override - public void write(JsonWriter writer, List value) { - writer.writeNull(); - } - - @Override - public List read(JsonReader reader) { - return null; - } - } - - @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) public static class Prices { public BigDecimal price; public Optional bid = Optional.empty(); @@ -177,36 +165,37 @@ public void selectsWholeValueAndDirectChildren() { expectThrows(ForyJsonException.class, () -> json.fromJson("{\"price\":\"10\"}", Prices.class)); } - @JsonDefaultCodec({TaggedDecimalCodec.class, TaggedOptionalCodec.class}) - public static class ListForm { + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) + public static class SingleForm { public BigDecimal price; public Optional bid = Optional.empty(); } - @JsonDefaultCodec(TaggedDecimalCodec.class) - @JsonDefaultCodec(TaggedOptionalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) + @JsonDefaultCodec(type = Optional.class, codec = TaggedOptionalCodec.class) public static class RepeatedForm { public BigDecimal price; public Optional bid = Optional.empty(); } @Test - public void listAndRepeatedFormsPreferExactParameterizedTarget() { + public void wholeTypeMatchWinsOverChildFill() { ForyJson json = newJson(); - ListForm list = new ListForm(); - list.price = TEN; - list.bid = Optional.of(TEN); + SingleForm single = new SingleForm(); + single.price = TEN; + single.bid = Optional.of(TEN); RepeatedForm repeated = new RepeatedForm(); repeated.price = TEN; repeated.bid = Optional.of(TEN); + // Without an Optional default, the BigDecimal default fills the Optional content. + assertEquals(json.toJson(single), "{\"price\":\"d:10\",\"bid\":\"d:10\"}"); + assertEquals(json.fromJson("{\"bid\":\"d:10\"}", SingleForm.class).bid, Optional.of(PLAIN_TEN)); String expected = "{\"price\":\"d:10\",\"bid\":\"od:10\"}"; - assertEquals(json.toJson(list), expected); assertEquals(json.toJson(repeated), expected); - assertEquals(json.fromJson(expected, ListForm.class).bid, Optional.of(PLAIN_TEN)); assertEquals(json.fromJson(expected, RepeatedForm.class).bid, Optional.of(PLAIN_TEN)); } - @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) public static class Base { public BigDecimal inherited; } @@ -215,7 +204,7 @@ public static class Child extends Base { public BigDecimal own; } - @JsonDefaultCodec(OtherDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = OtherDecimalCodec.class) public static class Overriding extends Base { public BigDecimal own; } @@ -234,7 +223,7 @@ public void superclassDefaultsApplyAndSubclassReplacesThem() { assertEquals(json.fromJson("{\"inherited\":\"o:10\"}", Overriding.class).inherited, PLAIN_TEN); } - @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) public static class Created { private final BigDecimal price; private final Optional bid; @@ -270,7 +259,7 @@ public void creatorParameters() { "{\"price\":\"d:10\",\"bid\":\"d:10\"}"); } - @JsonDefaultCodec(TaggedIntegerCodec.class) + @JsonDefaultCodec(type = Integer.class, codec = TaggedIntegerCodec.class) public static class Counts { public int primitive; public Integer boxed; @@ -294,7 +283,7 @@ public static class Plain { } @JsonMixin(target = Plain.class) - @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) public interface PlainMixin {} @Test @@ -308,31 +297,30 @@ public void mixinSuppliesDefaults() { } @JsonMixin(target = RepeatedForm.class) - @JsonDefaultCodec(OtherDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = OtherDecimalCodec.class) public interface RepeatedFormMixin {} - @JsonMixin(target = ListForm.class) - @JsonDefaultCodec(OtherDecimalCodec.class) - @JsonDefaultCodec(TaggedOptionalCodec.class) - public interface ListFormMixin {} + @JsonMixin(target = SingleForm.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = OtherDecimalCodec.class) + @JsonDefaultCodec(type = Optional.class, codec = TaggedOptionalCodec.class) + public interface SingleFormMixin {} @Test public void mixinReplacesBothDeclarationForms() { ForyJson json = newJsonBuilder() .registerMixin(RepeatedFormMixin.class) - .registerMixin(ListFormMixin.class) + .registerMixin(SingleFormMixin.class) .build(); RepeatedForm repeated = new RepeatedForm(); repeated.price = TEN; repeated.bid = Optional.of(TEN); - // The single Mixin declaration replaces the target's repeated ones, Optional - // included. + // The single Mixin declaration replaces the target's repeated ones, Optional included. assertEquals(json.toJson(repeated), "{\"price\":\"o:10\",\"bid\":\"o:10\"}"); - ListForm list = new ListForm(); - list.price = TEN; - list.bid = Optional.of(TEN); - assertEquals(json.toJson(list), "{\"price\":\"o:10\",\"bid\":\"od:10\"}"); + SingleForm single = new SingleForm(); + single.price = TEN; + single.bid = Optional.of(TEN); + assertEquals(json.toJson(single), "{\"price\":\"o:10\",\"bid\":\"od:10\"}"); } /** Owns its whole representation, so its elements are not a child slot a default can fill. */ @@ -352,7 +340,7 @@ public DecimalBag read(JsonReader reader) { @JsonCodec(DecimalBagCodec.class) public static class DecimalBag extends java.util.ArrayList {} - @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) public static class WithBag { public DecimalBag bag; public List registered; @@ -384,7 +372,7 @@ public List read(JsonReader reader) { assertEquals(json.toJson(value), "{\"bag\":\"bag:1\",\"registered\":\"list:1\"}"); } - @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) public static class WithList { public List values; } @@ -415,20 +403,20 @@ public List read(JsonReader reader) { assertEquals(module.toJson(value), "{\"values\":\"factory:1\"}"); } - @JsonDefaultCodec(TaggedIntegerCodec.class) + @JsonDefaultCodec(type = Integer.class, codec = TaggedIntegerCodec.class) public static class IntArrays { public int[] primitive; public Integer[] boxed; } @Test - public void primitiveArrayElementsMatchTheirWrapper() { + public void primitiveArrayKeepsItsMapping() { ForyJson json = newJson(); IntArrays value = new IntArrays(); value.primitive = new int[] {1, 2}; value.boxed = new Integer[] {3}; String text = json.toJson(value); - assertEquals(text, "{\"primitive\":[\"i:1\",\"i:2\"],\"boxed\":[\"i:3\"]}"); + assertEquals(text, "{\"primitive\":[1,2],\"boxed\":[\"i:3\"]}"); IntArrays read = json.fromJson(text, IntArrays.class); assertEquals(read.primitive, new int[] {1, 2}); assertEquals(read.boxed, new Integer[] {3}); @@ -438,7 +426,7 @@ public void primitiveArrayElementsMatchTheirWrapper() { @JsonMixinRemove(JsonDefaultCodec.class) public interface RemoveSingleFromRepeated {} - @JsonMixin(target = ListForm.class) + @JsonMixin(target = SingleForm.class) @JsonMixinRemove(JsonDefaultCodec.List.class) public interface RemoveRepeatedFromSingle {} @@ -451,18 +439,19 @@ public void mixinRemovalClearsBothDeclarationForms() { .build(); RepeatedForm repeated = new RepeatedForm(); repeated.price = TEN; - ListForm list = new ListForm(); - list.price = TEN; + SingleForm single = new SingleForm(); + single.price = TEN; // An empty Optional without a codec keeps Fory's default null form. assertEquals(json.toJson(repeated), "{\"price\":1E+1,\"bid\":null}"); - assertEquals(json.toJson(list), "{\"price\":1E+1,\"bid\":null}"); + assertEquals(json.toJson(single), "{\"price\":1E+1,\"bid\":null}"); } @JsonMixin(target = Child.class) @JsonMixinRemove(JsonDefaultCodec.class) public interface ChildWithoutDefaults {} - @JsonDefaultCodec({TaggedDecimalCodec.class, TaggedIntegerCodec.class}) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) + @JsonDefaultCodec(type = Integer.class, codec = TaggedIntegerCodec.class) public static class TwoDefaultsBase { public BigDecimal price; public Integer count; @@ -471,7 +460,7 @@ public static class TwoDefaultsBase { public static class TwoDefaultsChild extends TwoDefaultsBase {} @JsonMixin(target = TwoDefaultsChild.class) - @JsonDefaultCodec(OtherDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = OtherDecimalCodec.class) public interface TwoDefaultsChildMixin {} @Test @@ -495,7 +484,7 @@ public void mixinRemovalOnTargetDropsInheritedDefaults() { assertEquals(json.toJson(base), "{\"inherited\":\"d:10\"}"); } - @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) public static class Box { public T value; public List values; @@ -526,7 +515,7 @@ public void typeVariablesMatchAfterResolution() { assertEquals(read.strings.value, "s"); } - @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) public static class FormattedCreator { private final BigDecimal price; @@ -547,7 +536,7 @@ public void declaredFormatOnCreatorParameterWins() { assertEquals(json.fromJson("{\"price\":\"10\"}", FormattedCreator.class).price(), PLAIN_TEN); } - @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) public interface DefaultsOnInterface {} public static class ImplementsDefaults implements DefaultsOnInterface { @@ -571,7 +560,7 @@ public Shape read(JsonReader reader) { } } - @JsonDefaultCodec(ShapeCodec.class) + @JsonDefaultCodec(type = Shape.class, codec = ShapeCodec.class) public static class Shapes { public Shape single; public List list; @@ -602,7 +591,7 @@ public void interfaceChildWithoutOrdinaryMapping() { assertEquals(read.map.get("k").name(), "e"); } - @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) public static class Shallow { public List> nested; public Map> nestedMap; @@ -623,7 +612,7 @@ public void onlyDirectChildrenAndMapValuesAreDefaulted() { assertEquals(read.atomic.get(0), PLAIN_TEN); } - @JsonDefaultCodec(TaggedIntegerCodec.class) + @JsonDefaultCodec(type = Integer.class, codec = TaggedIntegerCodec.class) public static class Keyed { public Map counts; } @@ -645,34 +634,7 @@ public void contentNullSkipStillAppliesAroundChildDefault() { assertEquals(read.floors, Collections.singletonList(BigDecimal.ONE)); } - /** Declares its value type through an intermediate generic superclass. */ - public abstract static class PrefixCodec extends AbstractJsonValueCodec {} - - public static final class InheritedDecimalCodec extends PrefixCodec { - @Override - public void write(JsonWriter writer, BigDecimal value) { - writer.writeString("x:" + value.toPlainString()); - } - - @Override - public BigDecimal read(JsonReader reader) { - return new BigDecimal(reader.readString().substring(2)); - } - } - - @JsonDefaultCodec(InheritedDecimalCodec.class) - public static class InheritedTarget { - public BigDecimal price; - } - - @Test - public void codecValueTypeResolvesThroughGenericSuperclass() { - InheritedTarget value = new InheritedTarget(); - value.price = TEN; - assertEquals(newJson().toJson(value), "{\"price\":\"x:10\"}"); - } - - @JsonDefaultCodec(TaggedIntegerCodec.class) + @JsonDefaultCodec(type = int.class, codec = TaggedIntegerCodec.class) public static class MergedCreator { private final int count; @@ -686,6 +648,25 @@ public int getCount() { } } + @JsonDefaultCodec(type = int.class, codec = TaggedIntegerCodec.class) + public static class PrimitiveTypeCounts { + public Integer boxed; + public List list; + } + + @Test + public void primitiveTypeMatchesWrapperOccurrences() { + ForyJson json = newJson(); + PrimitiveTypeCounts counts = new PrimitiveTypeCounts(); + counts.boxed = 6; + counts.list = Collections.singletonList(7); + String text = json.toJson(counts); + assertEquals(text, "{\"boxed\":\"i:6\",\"list\":[\"i:7\"]}"); + PrimitiveTypeCounts read = json.fromJson(text, PrimitiveTypeCounts.class); + assertEquals(read.boxed, Integer.valueOf(6)); + assertEquals(read.list, Collections.singletonList(7)); + } + @Test public void getterAndCreatorParameterShareTheDefault() { ForyJson json = newJson(); @@ -694,11 +675,15 @@ public void getterAndCreatorParameterShareTheDefault() { assertEquals(json.fromJson(text, MergedCreator.class).getCount(), 7); } - @JsonDefaultCodec(TaggedByteCodec.class) + @JsonDefaultCodec(type = Byte.class, codec = TaggedByteCodec.class) public static class Bytes { public byte[] data; } + public static class PlainBytes { + public byte[] data; + } + public static final class TaggedByteCodec extends AbstractJsonValueCodec { @Override public void write(JsonWriter writer, Byte value) { @@ -712,14 +697,16 @@ public Byte read(JsonReader reader) { } @Test - public void byteArrayElementsUseDefaultInEveryByteArrayFormat() { + public void byteArrayKeepsEveryByteArrayFormat() { Bytes value = new Bytes(); value.data = new byte[] {1, 2}; + PlainBytes plain = new PlainBytes(); + plain.data = value.data; for (org.apache.fory.json.annotation.JsonByteArray.Format format : org.apache.fory.json.annotation.JsonByteArray.Format.values()) { ForyJson json = newJsonBuilder().byteArrayFormat(format).build(); String text = json.toJson(value); - assertEquals(text, "{\"data\":[\"b:1\",\"b:2\"]}", format.name()); + assertEquals(text, json.toJson(plain), format.name()); assertEquals(json.fromJson(text, Bytes.class).data, new byte[] {1, 2}); } } @@ -736,7 +723,9 @@ public String read(JsonReader reader) { } } - @JsonDefaultCodec({TaggedDecimalCodec.class, TaggedByteCodec.class, TaggedStringCodec.class}) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) + @JsonDefaultCodec(type = Byte.class, codec = TaggedByteCodec.class) + @JsonDefaultCodec(type = String.class, codec = TaggedStringCodec.class) public static class Excluded { @JsonFormat(shape = JsonFormat.Shape.STRING) public BigDecimal formatted; @@ -790,7 +779,7 @@ public BigDecimal read(JsonReader reader) { } } - @JsonDefaultCodec(NullableTaggedCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = NullableTaggedCodec.class) public static class NullablePrices { @JsonProperty(include = JsonProperty.Include.ALWAYS) public BigDecimal price; @@ -815,7 +804,7 @@ public void defaultCodecOwnsNullWithDefaultSettings() { public interface Contract {} - @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) public interface AnnotatedContract {} public interface ExtendsAnnotated extends AnnotatedContract {} @@ -830,12 +819,12 @@ public static class ImplementsThroughSuperclass extends AnnotatedBase implements public BigDecimal price; } - @JsonDefaultCodec(JsonCodec.NoJsonValueCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = JsonCodec.NoJsonValueCodec.class) public static class SentinelTarget { public BigDecimal price; } - @JsonDefaultCodec(TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) public static class WildcardPrices { public List prices; } @@ -848,159 +837,6 @@ public void wildcardChildrenKeepTheirMapping() { assertEquals(newJson().toJson(value), "{\"prices\":[1E+1]}"); } - public static final class DecimalListCodec extends AbstractJsonValueCodec> { - @Override - public void write(JsonWriter writer, List value) { - writer.writeString("list:" + value.size()); - } - - @Override - public List read(JsonReader reader) { - reader.readString(); - return Collections.emptyList(); - } - } - - @JsonDefaultCodec(DecimalListCodec.class) - public static class ExactAndWildcardLists { - public List exact; - public List wildcard; - } - - @Test - public void propertyWildcardDoesNotMatchAnExactTarget() { - ExactAndWildcardLists value = new ExactAndWildcardLists(); - value.exact = Collections.singletonList(TEN); - value.wildcard = Collections.singletonList(TEN); - assertEquals(newJson().toJson(value), "{\"exact\":\"list:1\",\"wildcard\":[1E+1]}"); - } - - public static class Bucket extends java.util.ArrayList> {} - - public static final class StringBucketCodec extends AbstractJsonValueCodec> { - @Override - public void write(JsonWriter writer, Bucket value) { - writer.writeString("bucket:" + value.size()); - } - - @Override - public Bucket read(JsonReader reader) { - reader.readString(); - return new Bucket<>(); - } - } - - public static class Dictionary extends java.util.HashMap {} - - public static final class DecimalDictionaryCodec - extends AbstractJsonValueCodec> { - @Override - public void write(JsonWriter writer, Dictionary value) { - writer.writeString("dict:" + value.size()); - } - - @Override - public Dictionary read(JsonReader reader) { - reader.readString(); - return new Dictionary<>(); - } - } - - @JsonDefaultCodec({StringBucketCodec.class, DecimalDictionaryCodec.class}) - public static class TransformedContainers { - public Bucket bucket; - public Dictionary dictionary; - } - - @Test - public void containerSubclassTargetsMatchTheirDeclaredArguments() { - TransformedContainers value = new TransformedContainers(); - value.bucket = new Bucket<>(); - value.bucket.add(Collections.singletonList("a")); - value.dictionary = new Dictionary<>(); - value.dictionary.put("k", TEN); - assertEquals(newJson().toJson(value), "{\"bucket\":\"bucket:1\",\"dictionary\":\"dict:1\"}"); - } - - public static final class NestedBucketCodec extends AbstractJsonValueCodec>> { - @Override - public void write(JsonWriter writer, Bucket> value) { - writer.writeString("nested:" + value.size()); - } - - @Override - public Bucket> read(JsonReader reader) { - reader.readString(); - return new Bucket<>(); - } - } - - public static final class DeeperBucketCodec - extends AbstractJsonValueCodec>>> { - @Override - public void write(JsonWriter writer, Bucket>> value) { - writer.writeString("deeper:" + value.size()); - } - - @Override - public Bucket>> read(JsonReader reader) { - reader.readString(); - return new Bucket<>(); - } - } - - @JsonDefaultCodec(NestedBucketCodec.class) - public static class NestedBucketHolder { - public Bucket> bucket; - } - - @JsonDefaultCodec(DeeperBucketCodec.class) - public static class DeeperTargetHolder { - public Bucket> bucket; - } - - @Test - public void containerSubclassArgumentsAreNotConfusedWithTheirElementToken() { - Bucket> bucket = new Bucket<>(); - NestedBucketHolder nested = new NestedBucketHolder(); - nested.bucket = bucket; - assertEquals(newJson().toJson(nested), "{\"bucket\":\"nested:0\"}"); - DeeperTargetHolder deeper = new DeeperTargetHolder(); - deeper.bucket = bucket; - assertEquals(newJson().toJson(deeper), "{\"bucket\":[]}"); - } - - @SuppressWarnings("rawtypes") - public static final class RawListArrayCodec extends AbstractJsonValueCodec { - @Override - public void write(JsonWriter writer, List[] value) { - writer.writeNull(); - } - - @Override - public List[] read(JsonReader reader) { - return null; - } - } - - @JsonDefaultCodec(RawListArrayCodec.class) - public static class RawListArrayDefaults {} - - @Test - @SuppressWarnings("rawtypes") - public void rawArrayTargetComparesComponentTokens() { - org.apache.fory.json.resolver.JsonDefaultCodecs defaults = - org.apache.fory.json.resolver.JsonDefaultCodecs.of( - RawListArrayDefaults.class, - new org.apache.fory.json.resolver.JsonSharedRegistry(newJsonBuilder().buildConfig())); - // A language module may describe Array> as List[] with a parameterized component. - org.apache.fory.reflect.TypeRef kotlinStyle = - org.apache.fory.reflect.TypeRef.of( - List[].class, null, null, new org.apache.fory.reflect.TypeRef>() {}); - assertEquals(defaults.select(kotlinStyle), null); - assertTrue(defaults.select(org.apache.fory.reflect.TypeRef.of(List[].class)) != null); - } - public static final class Money { public final long cents; @@ -1033,7 +869,7 @@ public Money read(JsonReader reader) { } } - @JsonDefaultCodec(DefaultMoneyCodec.class) + @JsonDefaultCodec(type = Money.class, codec = DefaultMoneyCodec.class) public static class Wallet { public Money cash; public List coins; @@ -1072,7 +908,8 @@ public TreeNode read(JsonReader reader) { } /** The TreeNode default makes List select a child default, so ownership is checked. */ - @JsonDefaultCodec({TaggedDecimalCodec.class, TreeNodeCodec.class}) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) + @JsonDefaultCodec(type = TreeNode.class, codec = TreeNodeCodec.class) public static class TreeNode { public BigDecimal value; public List children; @@ -1108,52 +945,33 @@ public List read(JsonReader reader) { assertEquals(json.toJson(node), "{\"value\":\"d:10\",\"children\":\"list:1\"}"); } - public static final class BoundedListCodec - extends AbstractJsonValueCodec> { - @Override - public void write(JsonWriter writer, List value) { - writer.writeNull(); - } - - @Override - public List read(JsonReader reader) { - return null; - } - } - - @JsonDefaultCodec(BoundedListCodec.class) - public static class BoundedWildcardTarget { - public List numbers; - } - - @JsonDefaultCodec({TaggedDecimalCodec.class, OtherDecimalCodec.class}) + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = OtherDecimalCodec.class) public static class DuplicateTarget { public BigDecimal price; } - @JsonDefaultCodec(TaggedDecimalCodec.class) - @JsonDefaultCodec(OtherDecimalCodec.class) - public static class RepeatedDuplicateTarget { - public BigDecimal price; + @JsonDefaultCodec(type = int.class, codec = TaggedIntegerCodec.class) + @JsonDefaultCodec(type = Integer.class, codec = TaggedIntegerCodec.class) + public static class PrimitiveDuplicateTarget { + public int count; } - @JsonDefaultCodec(WildcardListCodec.class) - public static class NoConcreteTarget { + @JsonDefaultCodec(type = void.class, codec = TaggedDecimalCodec.class) + public static class VoidTarget { public BigDecimal price; } @Test public void invalidDeclarations() { ForyJson json = newJson(); - assertInvalid(json, DuplicateTarget.class, "Duplicate @JsonDefaultCodec target"); - assertInvalid(json, RepeatedDuplicateTarget.class, "Duplicate @JsonDefaultCodec target"); - assertInvalid(json, NoConcreteTarget.class, "does not declare a concrete value type"); + assertInvalid(json, DuplicateTarget.class, "Duplicate @JsonDefaultCodec type"); + assertInvalid(json, PrimitiveDuplicateTarget.class, "Duplicate @JsonDefaultCodec type"); + assertInvalid(json, VoidTarget.class, "Invalid @JsonDefaultCodec"); assertInvalid(json, ImplementsDefaults.class, "not from interface"); assertInvalid(json, ImplementsThroughSuperinterface.class, "not from interface"); assertInvalid(json, ImplementsThroughSuperclass.class, "not from interface"); - assertInvalid(json, SentinelTarget.class, "is not a codec"); - // Only a Kotlin codec's declaration-site variance reads as its bound. - assertInvalid(json, BoundedWildcardTarget.class, "does not declare a concrete value type"); + assertInvalid(json, SentinelTarget.class, "Invalid @JsonDefaultCodec"); } private static void assertInvalid(ForyJson json, Class type, String message) { diff --git a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt index bd7eccec38..e9f4063545 100644 --- a/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt +++ b/kotlin/fory-json-kotlin-ksp/src/main/kotlin/org/apache/fory/json/kotlin/ksp/KspModelBuilder.kt @@ -1199,10 +1199,10 @@ internal class KspModelBuilder( JSON_DEFAULT_CODEC -> { // Kotlin compiles a repeated declaration into the nested container annotation. result.annotations += "$JSON_DEFAULT_CODEC\$List" - annotation.arguments.forEach { argument -> - collectCodecType(argument.value, result.codecs) - collectCodecSupertypes(argument.value, result.types) - } + collectCodecType( + annotation.arguments.first { it.name?.asString() == "codec" }.value, + result.codecs, + ) } JSON_DEFAULT_CODEC_LIST -> annotation.arguments.forEach { argument -> @@ -1274,34 +1274,6 @@ internal class KspModelBuilder( } } - /** - * The runtime reads a default codec's target from the generic signatures of its supertypes, so a - * shrinker must neither drop nor merge the classes on the way to `JsonValueCodec`. - */ - private fun collectCodecSupertypes(value: Any?, result: MutableSet) { - when (value) { - is KSType -> - (actual(value.declaration) as? KSClassDeclaration)?.let { collectSupertypes(it, result) } - is Iterable<*> -> value.forEach { collectCodecSupertypes(it, result) } - } - } - - private fun collectSupertypes(declaration: KSClassDeclaration, result: MutableSet) { - declaration.superTypes.forEach { reference -> - val supertype = actual(reference.resolve().declaration) as? KSClassDeclaration - val name = supertype?.let(::binaryName) - if ( - supertype != null && - name != null && - !name.startsWith("java.") && - !name.startsWith("kotlin.") && - result.add(name) - ) { - collectSupertypes(supertype, result) - } - } - } - private fun collectEndpoints( target: KSClassDeclaration, mixin: KSClassDeclaration?, diff --git a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt index 838ea6a90c..50e9631678 100644 --- a/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt +++ b/kotlin/fory-json-kotlin/src/test/kotlin/org/apache/fory/json/kotlin/KotlinBuiltInCodecsTest.kt @@ -101,7 +101,7 @@ class KotlinBuiltInCodecsTest { override fun read(reader: JsonReader): Int = reader.readString().substring(2).toInt() } - @JsonDefaultCodec(TaggedIntCodec::class) + @JsonDefaultCodec(type = Int::class, codec = TaggedIntCodec::class) data class SignedAndUnsigned( val signed: Int, val unsigned: UInt, @@ -119,9 +119,10 @@ class KotlinBuiltInCodecsTest { override fun read(reader: JsonReader): Price = Price(reader.readString().substring(2).toLong()) } - @JsonDefaultCodec(TaggedPriceCodec::class) data class Priced(val price: Price) + @JsonDefaultCodec(type = Price::class, codec = TaggedPriceCodec::class) + data class Priced(val price: Price) - @JsonDefaultCodec(TaggedPriceCodec::class) + @JsonDefaultCodec(type = Price::class, codec = TaggedPriceCodec::class) data class BoxedPrices(val price: Price?, val prices: List) @Test @@ -142,80 +143,15 @@ class KotlinBuiltInCodecsTest { override fun read(reader: JsonReader): UInt = reader.readString().substring(2).toUInt() } - @JsonDefaultCodec(UIntTagCodec::class) data class UnsignedTarget(val value: UInt) + @JsonDefaultCodec(type = UInt::class, codec = UIntTagCodec::class) + data class UnsignedTarget(val value: UInt) @Test fun defaultCodecRejectsUnsignedTarget() { val error = assertFailsWith { fory.toJson(UnsignedTarget(1u)) } - assertTrue(error.message.orEmpty().contains("Kotlin unsigned type"), error.message) + assertTrue(error.message.orEmpty().contains("Invalid @JsonDefaultCodec"), error.message) } - class LongListArrayCodec : AbstractJsonValueCodec>>() { - override fun write(writer: JsonWriter, value: Array>) { - writer.writeString("arrays:${value.size}") - } - - override fun read(reader: JsonReader): Array> { - reader.readString() - return arrayOf(listOf(1L)) - } - } - - @JsonDefaultCodec(LongListArrayCodec::class) - class GenericArrayHolder(val values: Array>) - - class LongListCodec : AbstractJsonValueCodec>() { - override fun write(writer: JsonWriter, value: List) { - writer.writeString("longs:${value.size}") - } - - override fun read(reader: JsonReader): List { - reader.readString() - return listOf(1L) - } - } - - @JsonDefaultCodec(LongListCodec::class) class LongListHolder(val values: List) - - class AnyMapCodec : AbstractJsonValueCodec>() { - override fun write(writer: JsonWriter, value: Map) { - writer.writeString("any:${value.size}") - } - - override fun read(reader: JsonReader): Map { - reader.readString() - return emptyMap() - } - } - - // Kotlin writes Any as ? extends Object; the declaration must still be accepted. - @JsonDefaultCodec(AnyMapCodec::class, TaggedIntCodec::class) - data class AnyTargetDeclared(val count: Int) - - @Test - fun defaultCodecAcceptsKotlinAnyArguments() { - assertEquals("{\"count\":\"i:3\"}", fory.toJson(AnyTargetDeclared(3))) - } - - @Test - fun defaultCodecMatchesKotlinCollectionTarget() { - assertEquals("{\"values\":\"longs:2\"}", fory.toJson(LongListHolder(listOf(1L, 2L)))) - } - - class NestedArrayCodec : AbstractJsonValueCodec>>>() { - override fun write(writer: JsonWriter, value: List>>) { - writer.writeString("nested:${value.size}") - } - - override fun read(reader: JsonReader): List>> { - reader.readString() - return emptyList() - } - } - - @JsonDefaultCodec(NestedArrayCodec::class) - class NestedArrayHolder(val values: List>>) - open class OpenShape(val name: String) { override fun equals(other: Any?): Boolean = other is OpenShape && name == other.name @@ -230,7 +166,7 @@ class KotlinBuiltInCodecsTest { override fun read(reader: JsonReader): OpenShape = OpenShape(reader.readString().substring(2)) } - @JsonDefaultCodec(OpenShapeCodec::class) + @JsonDefaultCodec(type = OpenShape::class, codec = OpenShapeCodec::class) class ListedCreator private constructor( val shapes: List, @@ -244,7 +180,7 @@ class KotlinBuiltInCodecsTest { ) : this(sourceShapes, sourceByKey, true) } - @JsonDefaultCodec(OpenShapeCodec::class) + @JsonDefaultCodec(type = OpenShape::class, codec = OpenShapeCodec::class) class LocalCreator @JsonCreator constructor( @@ -268,23 +204,7 @@ class KotlinBuiltInCodecsTest { } } - @Test - fun defaultCodecMatchesNestedGenericArrayProperty() { - assertEquals( - "{\"values\":\"nested:1\"}", - fory.toJson(NestedArrayHolder(listOf(arrayOf(listOf(1L))))), - ) - } - - @Test - fun defaultCodecMatchesGenericArrayProperty() { - assertEquals( - "{\"values\":\"arrays:2\"}", - fory.toJson(GenericArrayHolder(arrayOf(listOf(1L), listOf(2L)))), - ) - } - - @JsonDefaultCodec(TaggedIntCodec::class) + @JsonDefaultCodec(type = Int::class, codec = TaggedIntCodec::class) class UnsignedCreator private constructor(val signed: Int, val unsigned: UInt, @get:JsonIgnore val selected: Boolean) { @JsonCreator(value = ["signed", "unsigned"]) From 68cee2a1cfbff108c0159e29bfb052813f8c66e6 Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 10 Nov 2026 09:59:44 +0100 Subject: [PATCH 25/26] fix(java): keep unresolved type-variable children out of class defaults Co-Authored-By: Claude Opus 5.5 --- docs/json/custom-codecs.md | 3 ++- .../fory/json/resolver/JsonDefaultCodecs.java | 12 ++++++++--- .../fory/json/resolver/JsonTypeResolver.java | 3 +-- .../fory/json/JsonDefaultCodecTest.java | 20 +++++++++++++++++++ 4 files changed, 32 insertions(+), 6 deletions(-) diff --git a/docs/json/custom-codecs.md b/docs/json/custom-codecs.md index efebe0ea19..4be88b3a1c 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -303,7 +303,8 @@ child member from the table above; a language module's own containers, such as S `byteArrayFormat`. A child is filled only where the container keeps its standard mapping: a registered codec or factory, a module, or a type declaration that owns the container keeps it unchanged. Deeper nesting is not searched, and a wildcard child such as `List` -keeps its mapping, as an explicit child member would reject it. +or an unresolved type variable such as `List` in a raw generic class keeps its mapping, as an +explicit child member would reject it. A default codec is used exactly like a property `JsonCodec`, so it receives and owns null as described above for every property it reaches. Properties that declare `JsonCodec`, `JsonFormat`, diff --git a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java index 0a84c26544..596fedae74 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -19,6 +19,8 @@ package org.apache.fory.json.resolver; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; @@ -215,11 +217,15 @@ private Class> codec(TypeRef type) { } /** - * A wildcard child is not concrete, which an explicit child member rejects as well, and a child a - * language module tags with its own semantic type keeps that module's mapping. + * A wildcard or unresolved type-variable child is not concrete, which an explicit child member + * rejects as well, and a child a language module tags with its own semantic type keeps that + * module's mapping. */ private Class> childCodec(TypeRef child) { - return child.getType() instanceof WildcardType || semantic(child) ? null : codec(child); + Type type = child.getType(); + return type instanceof WildcardType || type instanceof TypeVariable || semantic(child) + ? null + : codec(child); } /** A type such as a Kotlin {@code UInt} carried as {@code int} keeps its module's mapping. */ 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 5835505956..5baf70cb42 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 @@ -605,8 +605,7 @@ private JsonTypeInfo resolveTypeInfo(TypeRef declaredType, JsonCodec annotati /** * Resolves an occurrence's selected codecs. {@code annotation} is the declaring {@link - * JsonCodec}, or null for a class default, which never selects a child of a composite module - * codec. + * JsonCodec}, or null for a class default. */ private JsonTypeInfo resolveTypeInfo( TypeRef declaredType, diff --git a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java index d55eb26f71..67bee79965 100644 --- a/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -515,6 +515,26 @@ public void typeVariablesMatchAfterResolution() { assertEquals(read.strings.value, "s"); } + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) + public static class BoundedGroup { + public List values; + public T[] array; + } + + @Test + public void unresolvedTypeVariableChildrenKeepTheirMapping() { + ForyJson json = newJson(); + BoundedGroup group = new BoundedGroup<>(); + group.values = Collections.singletonList(TEN); + group.array = new BigDecimal[] {TEN}; + String text = json.toJson(group); + assertEquals(text, "{\"values\":[1E+1],\"array\":[1E+1]}"); + BoundedGroup read = json.fromJson(text, BoundedGroup.class); + assertEquals(read.values, Collections.singletonList(TEN)); + assertEquals(read.array.length, 1); + assertEquals(read.array[0], TEN); + } + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) public static class FormattedCreator { private final BigDecimal price; From ea1cd08c6269c9e339fbb6a373a21ad449cefbcf Mon Sep 17 00:00:00 2001 From: Pavel Ptashyts Date: Tue, 10 Nov 2026 11:28:47 +0100 Subject: [PATCH 26/26] docs(java): escape the annotation example in JsonDefaultCodec javadoc Co-Authored-By: Claude Opus 5.5 --- .../org/apache/fory/json/annotation/JsonDefaultCodec.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java index 5c1777df59..25b6c3aa1a 100644 --- a/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java @@ -31,10 +31,10 @@ * Selects a default codec for the properties of the annotated class that have one declared type. * Repeat the annotation for several types; one class may name each type at most once. * - *

{@code
- * @JsonDefaultCodec(type = BigDecimal.class, codec = PlainBigDecimalCodec.class)
+ * 
+ * @JsonDefaultCodec(type = BigDecimal.class, codec = PlainBigDecimalCodec.class)
  * public class Invoice { ... }
- * }
+ *
* *

A property or creator parameter whose raw type equals {@link #type()} uses the codec as if it * declared {@code @JsonCodec(value = ...)}; a primitive and its wrapper are the same type.