【发布时间】:2020-08-01 06:00:15
【问题描述】:
我正在尝试在我现有的 Java 项目中开始使用 Kotlin,但 Jackson 没有在我的 Kotlin 对象中检测到 @JsonProperty(而它与 Java 对象完美配合)。
有什么方法可以配置 Jackson 以使其在 Kotlin 上像在 Java 上一样工作?
这是 Java 类:
public class TestJavaObj {
@JsonProperty
private String includeMe;
private String dontIncludeMe;
public TestJavaObj(String includeMe, String dontIncludeMe) {
this.includeMe = includeMe;
this.dontIncludeMe = dontIncludeMe;
}
}
还有 Kotlin 类:
class TestKotlinObj(
@JsonProperty val includeMe: String,
val dontIncludeMe : String?
)
这里是测试代码:
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper()
.registerModule(new KotlinModule()) //jackson-module-kotlin
.configure(MapperFeature.AUTO_DETECT_GETTERS, false)
.configure(MapperFeature.AUTO_DETECT_CREATORS, false)
.configure(MapperFeature.AUTO_DETECT_FIELDS, false)
.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false)
.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
TestJavaObj javaObj = new TestJavaObj("hello", "world");
TestKotlinObj kotlinObj = new TestKotlinObj("hello", "world");
System.out.println("Expected: " + mapper.writeValueAsString(javaObj));
System.out.println("Got: " + mapper.writeValueAsString(kotlinObj));
}
这是输出:
Expected: {"includeMe":"hello"}
Got: {}
我的 gradle 文件中的版本号:
kotlin_version = '1.3.72'
...
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
...
apply plugin: 'kotlin'
...
compile('com.fasterxml.jackson.core:jackson-annotations:2.10.3')
compile('com.fasterxml.jackson.module:jackson-module-kotlin:2.9.8')
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
【问题讨论】:
-
@unzila 似乎是关于向 bean 类添加自定义序列化程序。我想做的是让 Kotlin 类序列化以与 Java 序列化相同的方式工作。
标签: java kotlin serialization jackson