0

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?

krown_loki
  • 17
  • 4
  • Could you take the input as a String and then use ObjectMapper to convert the request into the form you want to consume? Also, you can try using 2 @JsonProperty, one for getter and other for setter for example: please checkout this question: https://stackoverflow.com/questions/8560348/different-names-of-json-property-during-serialization-and-deserialization – Dhruv Patel Sep 10 '22 at 19:13
  • No, unfortunately client wants to send request body exactly without key field in Map value. I don't understand if I can do that with `@JsonProperty` on setter method. – krown_loki Sep 12 '22 at 01:50

1 Answers1

0

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,
    ...
}
krown_loki
  • 17
  • 4