Skip to content

Commit db939c7

Browse files
committed
add findeSerializer
1 parent 8d80860 commit db939c7

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/main/kotlin/com/fasterxml/jackson/module/kotlin/KotlinAnnotationIntrospector.kt

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,14 @@ import java.lang.reflect.AccessibleObject
1111
import java.lang.reflect.Constructor
1212
import java.lang.reflect.Field
1313
import java.lang.reflect.Method
14+
import kotlin.reflect.KClass
1415
import kotlin.reflect.KFunction
1516
import kotlin.reflect.KMutableProperty1
1617
import kotlin.reflect.KProperty1
1718
import kotlin.reflect.KType
1819
import kotlin.reflect.full.createType
1920
import kotlin.reflect.full.declaredMemberProperties
21+
import kotlin.reflect.full.memberProperties
2022
import kotlin.reflect.jvm.*
2123

2224

@@ -59,6 +61,39 @@ internal class KotlinAnnotationIntrospector(private val context: Module.SetupCon
5961
return super.findCreatorAnnotation(config, a)
6062
}
6163

64+
// Find a serializer to handle the case where the getter returns an unboxed value from the value class.
65+
override fun findSerializer(am: Annotated): ValueClassBoxSerializer? = when (am) {
66+
is AnnotatedMethod -> {
67+
val getter = am.member.apply {
68+
// If the return value of the getter is a value class,
69+
// it will be serialized properly without doing anything.
70+
if (this.returnType.isUnboxableValueClass()) return null
71+
}
72+
73+
val kotlinProperty = getter
74+
.declaringClass
75+
.kotlin
76+
.let {
77+
// KotlinReflectionInternalError is raised in GitHub167 test,
78+
// but it looks like an edge case, so it is ignored.
79+
try {
80+
it.memberProperties
81+
} catch (e: Error) {
82+
null
83+
}
84+
}?.find { it.javaGetter == getter }
85+
86+
(kotlinProperty?.returnType?.classifier as? KClass<*>)
87+
?.takeIf { it.isValue }
88+
?.let { outerClazz ->
89+
@Suppress("UNCHECKED_CAST")
90+
ValueClassBoxSerializer(outerClazz as KClass<Any>, getter.returnType)
91+
}
92+
}
93+
// Ignore the case of AnnotatedField, because JvmField cannot be set in the field of value class.
94+
else -> null
95+
}
96+
6297
/**
6398
* Subclasses can be detected automatically for sealed classes, since all possible subclasses are known
6499
* at compile-time to Kotlin. This makes [com.fasterxml.jackson.annotation.JsonSubTypes] redundant.

0 commit comments

Comments
 (0)