gpt4 book ai didi

java - jackson 与 Kotlin :如何仅序列化带注释的属性

转载 作者:行者123 更新时间:2023-12-02 12:37:27 33 4
gpt4 key购买 nike

我试图在现有的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;
}
}

序列化对象时不考虑哪个。

查看相关问题: Kotlin data class Jackson @JsonProperty not honored

关于java - jackson 与 Kotlin :如何仅序列化带注释的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61293570/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com