首页 > 解决方案 > 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?

标签: javaserializationkotlinjacksondeserialization

解决方案


怎么样:

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 中创建计算属性,例如:

但是这些都有自己的复杂性,即使这种复杂性不在 DTO 类中。我不确定这些对我更有吸引力,但你可以看看它们是否对你有吸引力。


推荐阅读