Search code examples
springspring-bootspring-restcontrollerhttp-request-parameters

How to use a custom deserializer with Spring @RequestParam


I have an interface that's not aware of its implementations (module-wise):

public interface SomeInterface {
}

and an enum implementing it:

public enum SomeInterfaceImpl {
}

I have a @RestController:

@RequestMapping(method = RequestMethod.GET)
public List<SomeClass> find(@RequestParam(value = "key", required = false) SomeInterface someInt,
                            HttpServletResponse response){
}

Although Jackson is aware that it should deserialize SomeInterface as SomeInterfaceImpl as follows:

public class DefaultSomeInterfaceDeserializer extends JsonDeserializer<SomeInterface> {
    @Override
    public SomeInterface deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        return parser.readValuesAs(SomeInterfaceImpl.class).next();
    }
}

and:

@Configuration
public class MyJacksonConfiguration implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        if(bean instanceof Jackson2ObjectMapperBuilder){
            Jackson2ObjectMapperBuilder builder = (Jackson2ObjectMapperBuilder) bean;
            builder.deserializerByType(SomeInterface.class, new DefaultSomeInterfaceDeserializer());
        } 
        return bean;
    }
}

and successfully serializes and deserializes SomeInterface as SomeInterfaceImpl in the @RequestBody, it doesn't seem to have any effect on mapping SomeInterface to SomeInterfaceImpl with @RequestParam. How do I overcome this?


Solution

  • Having a Converter in the application context as M.Denium suggested does the job:

    @Component
    public class SomeInterfaceConverter implements Converter<String, SomeInterface> {
    
        @Override
        public SomeInterface convert(String value) {
            return new SomeInterfaceImpl(value);
        }
    }