stefan94452
stefan94452

Reputation: 111

How to convert a @RequestParam Map<String, String> to a custom a Map<>

I'm trying to convert a @RequestParam Map<String, String> to my own Map<Enum, Long> and I was wondering how to do it. My service needs to get this converted Map<Enum, Long> and I really would like to avoid an Object which capsules my enum and id.

This is necessary, because the endpoint is called with api/suff?FOO=1234&BAR=4567 and only one of them is mandatory for this service.

I already tried to create my own org.springframework.core.convert.converter.Converter with Converter<String, Map<Enum, Long>>. But I couldn't managed to convert it.

Currently my endpoint looks like that:

@GetMapping
public ResponseEntity<Stuff> getByIds(@RequestParam @NotEmpty @Size(max = 2) Map<Enum, Long> map) {
    return new ResponseEntity<>(someService.getStuff(map), HttpStatus.OK);
}

Is there a way to implement a custom converter for this case or do I have to follow an other approach?

Upvotes: 1

Views: 417

Answers (1)

Gyan
Gyan

Reputation: 1176

I'd vote for an alternate approach to achieve this -

@GetMapping
public ResponseEntity<Stuff> getByIds(@RequestParam(value="FOO", required = false) 
    String fooValue, @RequestParam(value="BAR", required = false) String barValue) {

    //Assuming you already have an ExceptionAdvice/handler for issues with the values passed
    Map<Enum, Long> map = new HashMap<Enum, Long>();
    if(null != fooValue){
        map.put("FOO", Enum.parse(fooValue));
    }
    if(null != barValue){
        map.put("BAR", Long.valueOf(barValue));
    }
    return new ResponseEntity<>(someService.getStuff(map), HttpStatus.OK);
}

I am unsure if this oversimplifies your API - that's a judgement call I'd expect.

Upvotes: 2

Related Questions