简体   繁体   中英

How to serialize request object without field name in Spring Boot?

I have simple REST Controller (in Kotlin) method with @RequestBody object.

@PostMappging(...)
fun postTestFunction(@RequestBody data: ExampleObject) {
    ...
}

Where ExampleObject is:

class ExampleObject(
    @JsonProperty("paramOne")
    val paramOne: Map<String, Int>,
    @JsonProperty("paramTwo")
    val paramTwo: String
)

That request can be send with next body:

{
    "paramOne": {
        "test": 1 // Here I can write any number of Map<String, Int>
    },
    "paramTwo": "test"
}

But I need another request body something like this:

{
    "test": 1, // I need  any number of Map<String, Int> without field name "paramOne"
    "paramTwo": "test"
}

What should I do to send request body with Map field (String, Int) but without field name?

I found solution. It's need to use @JsonAnySetter annotation. I changed ExampleObject to:

class ExampleObject(
    @JsonProperty("paramTwo")
    val paramTwo: String
) {
    @JsonProperty("paramOne")
    val paramOne = MutableMap<String, Int> = mutableMapOf()

    @JsonAnySetter
    fun setParamOne(key: String, value: Int) {
        paramOne[key] = value
    }
}

And now I can send request body the way I wanted. All fields that don't match with declared @JsonProperty annotation will be assigned to property with @JsonAnySetter method.

{
    "paramTwo": "data",
    "testStringOne": 1,
    "testStringTwo": 2,
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM