diff --git a/src/main/kotlin/com/github/avrokotlin/avro4k/FieldNaming.kt b/src/main/kotlin/com/github/avrokotlin/avro4k/FieldNaming.kt index c71827da..b24a6482 100644 --- a/src/main/kotlin/com/github/avrokotlin/avro4k/FieldNaming.kt +++ b/src/main/kotlin/com/github/avrokotlin/avro4k/FieldNaming.kt @@ -21,4 +21,11 @@ class FieldNaming(private val name: String, annotations: List) { * Takes into account @AvroName. */ fun name(): String = extractor.name() ?: name + + + /** + * Returns the avro aliases for the current element. + * Takes into account @AvroAlias. + */ + fun aliases(): List = extractor.aliases() } \ No newline at end of file diff --git a/src/main/kotlin/com/github/avrokotlin/avro4k/decoder/RecordDecoder.kt b/src/main/kotlin/com/github/avrokotlin/avro4k/decoder/RecordDecoder.kt index 927b476a..25b0cdf3 100644 --- a/src/main/kotlin/com/github/avrokotlin/avro4k/decoder/RecordDecoder.kt +++ b/src/main/kotlin/com/github/avrokotlin/avro4k/decoder/RecordDecoder.kt @@ -85,6 +85,13 @@ class RecordDecoder( if (record.hasField(resolvedFieldName())) { return record.get(resolvedFieldName()) } + + FieldNaming(desc, currentIndex).aliases().forEach { + if (record.hasField(it)) { + return record.get(it) + } + } + return null } diff --git a/src/test/kotlin/com/github/avrokotlin/avro4k/decoder/AvroAliasTest.kt b/src/test/kotlin/com/github/avrokotlin/avro4k/decoder/AvroAliasTest.kt new file mode 100644 index 00000000..d57c3817 --- /dev/null +++ b/src/test/kotlin/com/github/avrokotlin/avro4k/decoder/AvroAliasTest.kt @@ -0,0 +1,23 @@ +package com.github.avrokotlin.avro4k.decoder + +import com.github.avrokotlin.avro4k.Avro +import com.github.avrokotlin.avro4k.AvroAlias +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.shouldBe +import kotlinx.serialization.Serializable +import org.apache.avro.generic.GenericData + +@Serializable +data class OldFooString(val s: String) +@Serializable +data class FooStringWithAlias(@AvroAlias("s") val str: String) + +class AvroAliasTest : FunSpec({ + + test("decode with alias") { + val schema = Avro.default.schema(OldFooString.serializer()) + val record = GenericData.Record(schema) + record.put("s", "hello") + Avro.default.fromRecord(FooStringWithAlias.serializer(), record) shouldBe FooStringWithAlias("hello") + } +}) \ No newline at end of file