我正在尝试在现有的 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"
最佳答案
指定注释use-site target :
class TestKotlinObj(
@get:JsonProperty val includeMe: String,
val dontIncludeMe : String
)
结果:
Expected: {"includeMe":"hello"}
Got: {"includeMe":"hello"}
背景:
翻译成Java字节码的类只有一个构造函数参数注释:
public final class TestKotlinObj {
@NotNull // no annotation here
private final String includeMe;
@NotNull
private final String dontIncludeMe;
@NotNull // nor here
public final String getIncludeMe() {
return this.includeMe;
}
@NotNull
public final String getDontIncludeMe() {
return this.dontIncludeMe;
}
// but here
// vvvv
public TestKotlinObj(@JsonProperty @NotNull String includeMe, @NotNull String dontIncludeMe) {
Intrinsics.checkParameterIsNotNull(includeMe, "includeMe");
Intrinsics.checkParameterIsNotNull(dontIncludeMe, "dontIncludeMe");
super();
this.includeMe = includeMe;
this.dontIncludeMe = dontIncludeMe;
}
}
序列化对象时不会考虑这一点。
关于java - Jackson 与 Kotlin : how to serialize only annotated properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61293570/