简体   繁体   中英

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?

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.

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