2

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?

Hasan Can Saral
  • 2,950
  • 5
  • 43
  • 78
  • 1
    converting request params doesn't use jackson (why should it it isn't json). You need a custom `Converter` for that which converts from a `String` to your implemenation. – M. Deinum Feb 26 '20 at 10:52

1 Answers1

2

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);
    }
}
Hasan Can Saral
  • 2,950
  • 5
  • 43
  • 78