我试图在现有的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"
答案 0 :(得分:3)
指定注释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;
}
}
序列化对象时不考虑哪个。
答案 1 :(得分:1)
尝试将Kotlin类更改为此:
tag={id:post}
您当前拥有的Kotlin类可能与java中的该类等效(显然不起作用):
tag.update({id:post})