diff --git a/ci/tasks/kotlin.py b/ci/tasks/kotlin.py index ead6749bf5..e23fd66076 100644 --- a/ci/tasks/kotlin.py +++ b/ci/tasks/kotlin.py @@ -34,9 +34,12 @@ "PlatformAccount", "PlatformBox", "PlatformCircle", + "PlatformContainerDefaults", + "PlatformDefaultCodecs", "PlatformDefaults", "PlatformDirectOverride", "PlatformId", + "PlatformInheritedDefaults", "PlatformMarker", "PlatformNullHandling", "PlatformOpen", @@ -47,6 +50,7 @@ CORPUS_MIXIN_TARGETS = { "PlatformDefaultMixin": "PlatformDefaultTarget", "PlatformJavaProfileMixin": "PlatformJavaProfile", + "PlatformMixinDefaults": "PlatformMixinDefaultsTarget", "PlatformMixinOverrideAnnotations": "PlatformMixinOverride", } 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..4be88b3a1c 100644 --- a/docs/json/custom-codecs.md +++ b/docs/json/custom-codecs.md @@ -266,6 +266,63 @@ 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(type = BigDecimal.class, codec = 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 +} +``` + +`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 raw type equals `type` uses the codec as if it declared +`@JsonCodec(value = ...)`. + +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, 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` +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`, +`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 `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 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 Kotlin uses the same codec registrations and `JsonCodec` annotation. Apply property annotations to @@ -352,13 +409,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/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..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 @@ -37,6 +37,16 @@ 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 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 f7037dcd40..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 @@ -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,60 @@ public class PlatformTokenCodec : AbstractJsonValueCodec() { } } +public class PlatformDefaultTokenCodec : AbstractJsonValueCodec() { + 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(type = PlatformToken::class, codec = PlatformDefaultTokenCodec::class) +public data class PlatformDefaultCodecs( + public val token: PlatformToken, + public val tokens: List, +) + +@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(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 : AbstractJsonValueCodec() { + 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(type = PlatformToken::class, codec = PlatformDefaultTokenCodec::class) +@JsonDefaultCodec(type = PlatformLabel::class, codec = 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 55bc3948b0..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 @@ -101,6 +101,32 @@ public class KspRetentionResourceTest { rules("PlatformDirectOverride"), "$PACKAGE.PlatformDirectOverrideCodec", ) + val defaultCodecs = rules("PlatformDefaultCodecs") + assertConstructor(defaultCodecs, "$PACKAGE.PlatformDefaultTokenCodec") + assertTrue( + defaultCodecs.contains("@interface org.apache.fory.json.annotation.JsonDefaultCodec\n"), + defaultCodecs, + ) + assertTrue( + 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("@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 mixinDefaults = mixinRules("PlatformMixinDefaults") + assertConstructor(mixinDefaults, "$PACKAGE.PlatformDefaultTokenCodec") + assertConstructor(mixinDefaults, "$PACKAGE.PlatformLabelCodec") val mixin = mixinRules("PlatformJavaProfileMixin") assertTrue(mixin.contains("class $PACKAGE.PlatformJavaProfile"), mixin) assertTrue(mixin.contains("class $PACKAGE.PlatformJavaProfileMixin"), mixin) @@ -148,10 +174,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", @@ -159,6 +188,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/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/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..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 @@ -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"; @@ -104,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); @@ -225,6 +228,30 @@ 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)) { + 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, enums, or" + + " annotation types", + element); + } + } + } + } + private static TypeElement enclosingType(Element element) { Element current = element; while (current != null && !(current instanceof TypeElement)) { @@ -476,6 +503,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 +637,39 @@ 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, "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()); + } + } + + 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"; @@ -671,9 +739,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 73b9c2a09f..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 @@ -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; @@ -118,6 +120,71 @@ 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(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" + + " 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 defaultCodecOnEnumFailsCompilation() throws Exception { + CompilationResult result = + compile( + "test.DefaultStatus", + "package test;\n" + + "import org.apache.fory.json.annotation.JsonDefaultCodec;\n" + + "@JsonDefaultCodec(type = Long.class, codec = 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 = + 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(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" + + "}\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); + } + @Test public void mixinTypeCodecRules() throws Exception { CompilationResult result = @@ -1617,6 +1684,101 @@ 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\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" + + " }\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 = + " 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(type = Long.class, codec = 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(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( + 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); + // 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 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..25b6c3aa1a --- /dev/null +++ b/java/fory-json/src/main/java/org/apache/fory/json/annotation/JsonDefaultCodec.java @@ -0,0 +1,77 @@ +/* + * 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 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. + * + *
+ * @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. + * 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 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. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Repeatable(JsonDefaultCodec.List.class) +public @interface JsonDefaultCodec { + /** 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 + @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..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 @@ -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; @@ -1561,6 +1562,7 @@ private static JsonCreatorInfo buildRecordCreatorInfo( resolved, rawTypes[i], builder.codecAnnotation(), + builder.creatorDefault(resolved, ownerType), builder.valueCodecClass(), builder.formatAnnotation(), builder.creatorUnboxedRequired, @@ -1702,6 +1704,7 @@ private static JsonCreatorInfo buildCreatorInfo( resolved, rawTypes[i], codecAnnotation, + builder.creatorDefault(resolved, ownerType), valueCodecClass, builder.formatAnnotation(), builder.creatorUnboxedRequired, @@ -1775,6 +1778,12 @@ private static JsonCreatorInfo buildCreatorInfo( builder == null ? annotations.get(parameters[i], JsonUnwrapped.class) : builder.unwrappedAnnotation; + 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 @@ -1810,6 +1819,7 @@ private static JsonCreatorInfo buildCreatorInfo( resolved, rawTypes[i], codecAnnotation, + defaultCodec, valueCodecClass, formatAnnotation, false, @@ -1956,6 +1966,7 @@ private static JsonCreatorInfo buildObjectModelCreatorInfo( resolved, rawTypes[i], builder.codecAnnotation(), + builder.creatorDefault(resolved, ownerType), builder.valueCodecClass(), builder.formatAnnotation(), builder.creatorUnboxedRequired, @@ -3109,10 +3120,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) { @@ -3424,6 +3437,7 @@ private JsonFieldInfo build( ownerType, objectModelType, codecAnnotation, + usesDefaultCodec() ? annotations.defaultCodecs.select(logicalTypeRef(ownerType)) : null, valueCodecClass, formatAnnotation, rawValue, @@ -3510,6 +3524,30 @@ private JsonCodec codecAnnotation() { return codecAnnotation; } + /** + * 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 JsonDefaultCodecs.Selection creatorDefault( + TypeRef parameterType, TypeRef ownerType) { + if (!usesDefaultCodec()) { + return null; + } + return annotations.defaultCodecs.select( + hasLogicalMember() ? logicalTypeRef(ownerType) : parameterType); + } + + 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/meta/JsonCreatorFieldInfo.java b/java/fory-json/src/main/java/org/apache/fory/json/meta/JsonCreatorFieldInfo.java index 5dd14ef03e..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 @@ -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; @@ -46,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; @@ -67,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; @@ -75,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() { @@ -112,6 +145,7 @@ public JsonCreatorFieldInfo withName(String transformedName) { typeRef, rawType, codecAnnotation, + defaultCodec, valueCodecClass, formatAnnotation, unboxedRequired, @@ -157,7 +191,8 @@ public void resolveType(JsonTypeResolver resolver) { "JSON creator property " + name + " cannot select a codec or format for the unboxed logical type " - + typeRef); + + typeRef + + (defaultCodec == null ? "" : " selected by the class @JsonDefaultCodec")); } JsonTypeInfo canonical = resolver.withContentNullRead(resolver.getTypeInfo(typeRef), onContentNullRead); @@ -187,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 7b756e80bb..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 @@ -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; @@ -116,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; @@ -409,6 +411,7 @@ public JsonFieldInfo( TypeRef ownerType, TypeRef objectModelType, JsonCodec codecAnnotation, + JsonDefaultCodecs.Selection defaultCodec, Class> valueCodecClass, JsonFormat formatAnnotation, boolean rawValue, @@ -463,6 +466,7 @@ public JsonFieldInfo( readIndexAndWriteNull |= OMIT_EMPTY_MASK; } this.codecAnnotation = codecAnnotation; + this.defaultCodec = defaultCodec; this.valueCodecClass = valueCodecClass; this.formatAnnotation = formatAnnotation; this.writeAccessor = writeAccessor; @@ -592,6 +596,7 @@ public JsonFieldInfo withName(String transformedName, TypeRef ownerType) { ownerType, writeTypeRef != null ? writeTypeRef : readTypeRef, codecAnnotation, + defaultCodec, valueCodecClass, formatAnnotation, writesRawString(), @@ -914,22 +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); + + codecType + + (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; @@ -1262,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 new file mode 100644 index 0000000000..596fedae74 --- /dev/null +++ b/java/fory-json/src/main/java/org/apache/fory/json/resolver/JsonDefaultCodecs.java @@ -0,0 +1,302 @@ +/* + * 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.reflect.Type; +import java.lang.reflect.TypeVariable; +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.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.reflect.TypeRef; +import org.apache.fory.type.TypeUtils; +import org.apache.fory.type.Types; + +/** + * 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(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", + "kotlin.UShort", + "kotlin.UInt", + "kotlin.ULong", + "kotlin.UByteArray", + "kotlin.UShortArray", + "kotlin.UIntArray", + "kotlin.ULongArray"); + + private final Entry[] entries; + + 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 && (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 = registry.mixinOverrides(type, declaring, JsonDefaultCodec.class); + boolean repeatedReplaced = + registry.mixinOverrides(type, 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) { + 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; + } else { + for (Entry entry : declared) { + if (find(entries, entry.target) == null) { + entries.add(entry); + } + } + } + } + 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); + } + } + + 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 || semantic(type)) { + return null; + } + Class> codec = codec(type); + if (codec != null) { + return new Selection(codec, null, null, null); + } + Class rawType = type.getRawType(); + if (rawType.isArray()) { + // 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()) { + return null; + } + if (Collection.class.isAssignableFrom(rawType) || rawType == AtomicReferenceArray.class) { + codec = childCodec(CodecUtils.elementTypeRef(type)); + 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 Selection(null, null, codec, null); + } + if (Map.class.isAssignableFrom(rawType)) { + codec = childCodec(CodecUtils.mapKeyValueTypeRefs(type).f1); + return codec == null ? null : new Selection(null, null, null, codec); + } + return null; + } + + /** Returns the default whose type is the raw type of this occurrence, or null. */ + private Class> codec(TypeRef type) { + Class rawType = TypeUtils.wrap(type.getRawType()); + for (Entry entry : entries) { + if (entry.target == rawType) { + return entry.codecClass; + } + } + return null; + } + + /** + * 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) { + 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. */ + private static boolean semantic(TypeRef type) { + return type.getTypeExtMeta() != null && type.getTypeExtMeta().typeId() != Types.UNKNOWN; + } + + private static final class Entry { + private final Class target; + private final Class> codecClass; + + private Entry(Class target, Class> codecClass) { + this.target = target; + this.codecClass = codecClass; + } + } + + /** + * 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 Selection( + 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; + } + + /** Returns the complete-value codec, or {@code NoJsonValueCodec} for a child selection. */ + public Class> value() { + return value; + } + + public Class> elementCodec() { + return elementCodec; + } + + public Class> contentCodec() { + return contentCodec; + } + + public Class> valueCodec() { + return valueCodec; + } + + /** Returns whether this selection fills a child member rather than the complete value. */ + public boolean child() { + return value == JsonCodec.NoJsonValueCodec.class; + } + + @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..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 @@ -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, @@ -511,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..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 @@ -1270,6 +1270,44 @@ public A annotation( : overlay.annotation(declaration, annotationType); } + /** + * Returns whether a representation other than the standard container mapping owns this container + * 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(); + 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) { + 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..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 @@ -432,6 +432,35 @@ public JsonTypeInfo getTypeInfo(TypeRef declaredType, JsonCodec annotation) { } } + /** 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 = + selection.child() && sharedRegistry.ownsContainer(declaredType, this) + ? getTypeInfo(declaredType) + : resolveTypeInfo( + declaredType, + null, + selection.value(), + selection.elementCodec(), + selection.contentCodec(), + JsonCodec.NoMapKeyCodec.class, + selection.valueCodec()); + completeResolution(snapshot); + return result; + } catch (RuntimeException | Error e) { + rollbackResolution(snapshot); + throw e; + } finally { + endResolution(); + } + } + @Internal public JsonTypeInfo getTypeInfo( Type declaredType, Class fallback, Class> codecClass) { @@ -564,13 +593,30 @@ 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. + */ + 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; @@ -655,7 +701,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; 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..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 @@ -54,6 +54,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.JsonMixin; import org.apache.fory.json.annotation.JsonSubTypes; import org.apache.fory.json.annotation.JsonType; @@ -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,12 @@ private void registerCodecs(JsonCodec annotation) { registerCodec(annotation.valueCodec()); } + private void registerDefaultCodecs(JsonDefaultCodec annotation) { + if (annotation != null) { + registerCodec(annotation.codec()); + } + } + 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..67bee79965 --- /dev/null +++ b/java/fory-json/src/test/java/org/apache/fory/json/JsonDefaultCodecTest.java @@ -0,0 +1,1003 @@ +/* + * 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.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; +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)); + } + } + + @SuppressWarnings("rawtypes") + public static final class TaggedOptionalCodec extends AbstractJsonValueCodec { + @Override + public void write(JsonWriter writer, Optional value) { + writer.writeString("od:" + ((BigDecimal) 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)); + } + } + + @JsonDefaultCodec(type = BigDecimal.class, codec = 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(type = BigDecimal.class, codec = TaggedDecimalCodec.class) + public static class SingleForm { + public BigDecimal price; + public Optional bid = Optional.empty(); + } + + @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 wholeTypeMatchWinsOverChildFill() { + ForyJson json = newJson(); + 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(repeated), expected); + assertEquals(json.fromJson(expected, RepeatedForm.class).bid, Optional.of(PLAIN_TEN)); + } + + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) + public static class Base { + public BigDecimal inherited; + } + + public static class Child extends Base { + public BigDecimal own; + } + + @JsonDefaultCodec(type = BigDecimal.class, codec = 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(type = BigDecimal.class, codec = 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(type = Integer.class, codec = 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(type = BigDecimal.class, codec = 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(type = BigDecimal.class, codec = OtherDecimalCodec.class) + public interface RepeatedFormMixin {} + + @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(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. + assertEquals(json.toJson(repeated), "{\"price\":\"o:10\",\"bid\":\"o: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. */ + 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(type = BigDecimal.class, codec = 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(type = BigDecimal.class, codec = 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(type = Integer.class, codec = TaggedIntegerCodec.class) + public static class IntArrays { + public int[] primitive; + public Integer[] boxed; + } + + @Test + 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\":[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}); + } + + @JsonMixin(target = RepeatedForm.class) + @JsonMixinRemove(JsonDefaultCodec.class) + public interface RemoveSingleFromRepeated {} + + @JsonMixin(target = SingleForm.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; + 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(single), "{\"price\":1E+1,\"bid\":null}"); + } + + @JsonMixin(target = Child.class) + @JsonMixinRemove(JsonDefaultCodec.class) + public interface ChildWithoutDefaults {} + + @JsonDefaultCodec(type = BigDecimal.class, codec = TaggedDecimalCodec.class) + @JsonDefaultCodec(type = Integer.class, codec = TaggedIntegerCodec.class) + public static class TwoDefaultsBase { + public BigDecimal price; + public Integer count; + } + + public static class TwoDefaultsChild extends TwoDefaultsBase {} + + @JsonMixin(target = TwoDefaultsChild.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = 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(); + 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(type = BigDecimal.class, codec = 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(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; + + @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(type = BigDecimal.class, codec = TaggedDecimalCodec.class) + public interface DefaultsOnInterface {} + + 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(type = Shape.class, codec = 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(type = BigDecimal.class, codec = 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(type = Integer.class, codec = 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)); + } + + @JsonDefaultCodec(type = int.class, codec = 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; + } + } + + @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(); + String text = json.toJson(new MergedCreator(7)); + assertEquals(text, "{\"count\":\"i:7\"}"); + assertEquals(json.fromJson(text, MergedCreator.class).getCount(), 7); + } + + @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) { + writer.writeString("b:" + value); + } + + @Override + public Byte read(JsonReader reader) { + return Byte.valueOf(reader.readString().substring(2)); + } + } + + @Test + 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, json.toJson(plain), format.name()); + assertEquals(json.fromJson(text, Bytes.class).data, new byte[] {1, 2}); + } + } + + 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(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; + + @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); + } + + /** 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(type = BigDecimal.class, codec = 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(type = BigDecimal.class, codec = 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(type = BigDecimal.class, codec = JsonCodec.NoJsonValueCodec.class) + public static class SentinelTarget { + public BigDecimal price; + } + + @JsonDefaultCodec(type = BigDecimal.class, codec = 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]}"); + } + + 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(type = Money.class, codec = 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) { + 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(type = BigDecimal.class, codec = TaggedDecimalCodec.class) + @JsonDefaultCodec(type = TreeNode.class, codec = TreeNodeCodec.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(type = BigDecimal.class, codec = TaggedDecimalCodec.class) + @JsonDefaultCodec(type = BigDecimal.class, codec = OtherDecimalCodec.class) + public static class DuplicateTarget { + 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(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 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, "Invalid @JsonDefaultCodec"); + } + + 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())); + } +} 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..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 @@ -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,26 @@ 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 || + 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, enums, or annotation types", + it + ) + } for (symbol in resolver.getSymbolsWithAnnotation(JSON_MIXIN)) { if (!symbol.validate()) { deferred += symbol @@ -102,3 +123,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 cc55baa3af..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 @@ -47,6 +47,8 @@ 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_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" @@ -1083,31 +1085,77 @@ 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?, ): 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, @@ -1144,9 +1192,24 @@ 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 -> { + // Kotlin compiles a repeated declaration into the nested container annotation. + result.annotations += "$JSON_DEFAULT_CODEC\$List" + collectCodecType( + annotation.arguments.first { it.name?.asString() == "codec" }.value, + result.codecs, + ) + } + 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 c823513b21..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 @@ -37,6 +37,11 @@ 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 import org.apache.fory.json.writer.JsonWriter @@ -88,6 +93,145 @@ 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(type = Int::class, codec = TaggedIntCodec::class) + data class SignedAndUnsigned( + val signed: Int, + val unsigned: UInt, + val signedList: List, + 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(type = Price::class, codec = TaggedPriceCodec::class) + data class Priced(val price: Price) + + @JsonDefaultCodec(type = Price::class, codec = TaggedPriceCodec::class) + data class BoxedPrices(val price: Price?, val prices: List) + + @Test + 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) + assertEquals("{\"price\":\"p:10\",\"prices\":[\"p:20\"]}", json) + 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(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("Invalid @JsonDefaultCodec"), error.message) + } + + 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(type = OpenShape::class, codec = 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(type = OpenShape::class, codec = 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)) + } + } + + @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"]) + 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)) + 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,