java - Kotlin: Change the json property name depending on the @JsonView
问题描述
I am trying to use Jackson to serialize the same DTO object in 2 different ways, depending on the @JsonView
.
I want to use 2 different names for the same field. In one case I want to name the json property myField
(just like the class field name), in the other I want it to be named myInternalApiField
.
As a result I would like to see outcomes similar to the presented below:
Usage 1 (External API View):
{
"myField": "value1",
"myOtherField": "otherValue"
}
Usage 2 (Internal API View):
{
"myInternalApiField": "value1",
"myOtherField": "otherValue"
}
In my implementation in Java to achieve that I used the combination of custom getters, setters and @JsonView
annotation as below:
public class CustomDTO {
@JsonView(Views.ExternalApiView)
private String myField;
// Other fields here
@JsonView(Views.InternalApiView)
public String getMyInternalApiField() { return myField; }
@JsonView(Views.InternalApiView)
public void setMyInternalApiField(String value) { this.myField = value; }
@JsonView(Views.ExternalApiView)
public String getMyField() { return myField; }
@JsonView(Views.ExternalApiView)
public void setMyField(String value) { this.myField = value }
}
However I don't know how to properly achieve the same result in Kotlin.
I was thinking about using something like:
data class CustomDTO(
@get:[JsonView(Views.ExternalApiView) JsonProperty("myField")]
@get:[JsonView(Views.InternalApiView) JsonProperty("myInternalApiField")]
@set:[JsonView(Views.InternalApiView) JsonProperty("myField")]
@set:[JsonView(Views.InternalApiView) JsonProperty("myInternalApiField")]
var myField: String,
val myOtherField: String,
val myDifferentField: String
)
But this is not allowed in Kotlin.
Do you have any suggestions how to utilize the @JsonView
in Kotlin in the similar way as I did it in Java?
解决方案
怎么样:
data class CustomDTO(
@JsonView(ExternalApiView::class)
var myField: String,
val myOtherField: String,
val myDifferentField: String
) {
val myExternalField: String
@JsonView(InternalApiView::class)
get() {
return myField
}
}
看起来有些方法不需要在 DTO 中创建计算属性,例如:
- 使用Jackson Mixin
- 为特定调用创建自定义序列化程序
- 将自定义序列化程序与自定义注释相结合
但是这些都有自己的复杂性,即使这种复杂性不在 DTO 类中。我不确定这些对我更有吸引力,但你可以看看它们是否对你有吸引力。
推荐阅读
- powershell - Powershell - Start-Job - 传递基于变量的命令
- node.js - 如何让 Nodejs 在 CORS 中使用 k8 DNS 命名
- ruby-on-rails - 在 Rails 的顶级路径和嵌套路径中使用具有关联的相同控制器
- python - Python 包安装在 AmazonLinux 上
- c++ - 从一类调用函数到第二类导致串行 C++ 上的编码错误
- python - 函数总是返回 false
- c - 尝试释放 malloc 时出错
- react-native - 如何停止 ScrollView 滑动?
- r - 在 R 中运行具有特定数据的 ANOSIM?
- python - 通过在python中拆分输入文本来制作计算器