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?
CodePudding user response:
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,
...
}