如何获取Kotlin类中@JsonProperty注解的名称列表?
从Kotlin数据类中提取@JsonProperty注解值列表
方法一:使用Kotlin反射
首先确保项目中引入kotlin-reflect依赖(Gradle配置示例):
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
通过反射遍历类的成员属性,提取@JsonProperty注解的value值:
import com.fasterxml.jackson.annotation.JsonProperty import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.findAnnotation data class MyClass( @JsonProperty("title") var titleValue: String, @JsonProperty("body") var bodyValue: String ) fun main() { val jsonPropertyNames = MyClass::class.declaredMemberProperties .mapNotNull { prop -> prop.findAnnotation<JsonProperty>()?.value } println(jsonPropertyNames) // 输出: [title, body] }
逻辑说明:
- 获取类的所有成员属性
- 逐个查找属性上的
@JsonProperty注解 - 提取注解指定的名称,自动过滤无该注解的属性
方法二:借助Jackson的ObjectMapper
如果项目已集成Jackson,可直接用其API解析类的JSON属性名称:
import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.ObjectMapper data class MyClass( @JsonProperty("title") var titleValue: String, @JsonProperty("body") var bodyValue: String ) fun main() { val objectMapper = ObjectMapper() val beanDescription = objectMapper.deserializationConfig .introspect(objectMapper.typeFactory.constructType(MyClass::class.java)) val jsonPropertyNames = beanDescription.findProperties().map { it.name } println(jsonPropertyNames) // 输出: [title, body] }
这种方式无需额外引入反射依赖,直接利用Jackson的类信息解析能力,适合已用Jackson做序列化/反序列化的项目。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

