I have the following payload:
{
"KeyA": "ValueA",
"KeyB": "ValueB",
"KeyC": "ValueC"
...
"KeyZ": "ValueZ"
}
That I am able to parse properly in a spring boot controller with:
@PostMapping
public ResponseEntity<Object> createABC(
@RequestBody final Map<MyDTO, MyDTO> map
) {
For the sake of brevity, consider MyDTO as:
@Data
@ToString(includeFieldNames=false)
public class MyDTO implements Comparable<MyDTO> {
private final String name;
The problem is:
I can have duplicated keys on the input:
{
"KeyA": "ValueA",
"KeyA": "ValueA.1",
...
}
Which then gets deduplicated by the native Java Map implementation - only the second key gets saved and I am okay with that. I found out Guava Multimap that would allow me to do it. This would allow me to accept a map with duplicates and let me execute the custom logic on the controller/service layer.
The problem is that I can't find how to make spring boot parse this map in the controller without reformatting the request, I would like to keep it as it is. I was able to add the Object Mapper but I am failing to be able to receive this map from the request at the controller and use it.
Has anyone faced this issue before?
I'm not sure what you meant by this, but I assume that you are sending the request like this :
If you want to use
com.google.common.collect.Multimapthere is no other way to send a request.If you want to send a request in the form you mentioned in the question (withot [] brackets), as far as I can see, you have two options:
org.apache.commons.collections4.MultiValuedMapwith custom deserilizer;Here is how your custom deserilizer should look like:
Here is how endpoint shoud look like:
When you hit this endpoint, you should see output like this:
org.springframework.util.MultiValueMapIf you want to use this class, you shoud send your request body as
x-www-form-urlencoded. Here is an example from Postman:And finally, if you decide to use this option here is an example how controller method should look like:
Using this approach, you should see output like this: