如何使用带有 Spring @RequestParam 的自定义解串器
How to use a custom deserializer with Spring @RequestParam
我有一个不知道其实现的接口(模块方面):
public interface SomeInterface {
}
和实现它的枚举:
public enum SomeInterfaceImpl {
}
我有一个 @RestController
:
@RequestMapping(method = RequestMethod.GET)
public List<SomeClass> find(@RequestParam(value = "key", required = false) SomeInterface someInt,
HttpServletResponse response){
}
尽管 Jackson 知道它应该将 SomeInterface
反序列化为 SomeInterfaceImpl
,如下所示:
public class DefaultSomeInterfaceDeserializer extends JsonDeserializer<SomeInterface> {
@Override
public SomeInterface deserialize(JsonParser parser, DeserializationContext context) throws IOException {
return parser.readValuesAs(SomeInterfaceImpl.class).next();
}
}
和:
@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;
}
}
并成功将SomeInterface
序列化和反序列化为@RequestBody
中的SomeInterfaceImpl
,似乎对SomeInterface
到[=18=的映射没有任何影响] 和 @RequestParam
。我该如何克服这个问题?
按照 M.Denium 的建议在应用程序上下文中使用 Converter
可以完成工作:
@Component
public class SomeInterfaceConverter implements Converter<String, SomeInterface> {
@Override
public SomeInterface convert(String value) {
return new SomeInterfaceImpl(value);
}
}
我有一个不知道其实现的接口(模块方面):
public interface SomeInterface {
}
和实现它的枚举:
public enum SomeInterfaceImpl {
}
我有一个 @RestController
:
@RequestMapping(method = RequestMethod.GET)
public List<SomeClass> find(@RequestParam(value = "key", required = false) SomeInterface someInt,
HttpServletResponse response){
}
尽管 Jackson 知道它应该将 SomeInterface
反序列化为 SomeInterfaceImpl
,如下所示:
public class DefaultSomeInterfaceDeserializer extends JsonDeserializer<SomeInterface> {
@Override
public SomeInterface deserialize(JsonParser parser, DeserializationContext context) throws IOException {
return parser.readValuesAs(SomeInterfaceImpl.class).next();
}
}
和:
@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;
}
}
并成功将SomeInterface
序列化和反序列化为@RequestBody
中的SomeInterfaceImpl
,似乎对SomeInterface
到[=18=的映射没有任何影响] 和 @RequestParam
。我该如何克服这个问题?
按照 M.Denium 的建议在应用程序上下文中使用 Converter
可以完成工作:
@Component
public class SomeInterfaceConverter implements Converter<String, SomeInterface> {
@Override
public SomeInterface convert(String value) {
return new SomeInterfaceImpl(value);
}
}