我在我的Spring MVC(v3.2.0.RELEASE)Web應用程序下面的對象模型多態性對象模型:反序列化JSON使用Spring和JsonTypeInfo註釋
public class Order {
private Payment payment;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.WRAPPER_OBJECT)
@JsonSubTypes.Type(name = "creditCardPayment", value = CreditCardPayment.class)
public interface Payment {}
@JsonTypeName("creditCardPayment")
public class CreditCardPayment implements Payment {}
當我連載訂單類JSON,我得到以下結果(這是我想要什麼):
{
"payment" : {
"creditCardPayment": {
...
}
}
不幸的是,如果我走在上面JSON,並嘗試去連載它放回我的對象模型,我得到下面的異常:
Could not read JSON: Could not resolve type id 'creditCardPayment' into a subtype of [simple type, class Payment] at [Source: [email protected]; line: 1, column: 58] (through reference chain: Order["payment"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Could not resolve type id 'creditCardPayment' into a subtype of [simple type, class Payment] at [Source: [email protected]; line: 1, column: 58] (through reference chain: Order["payment"])
我的應用程序經由彈簧JavaConf配置,如下所示:
@Configuration
@EnableWebMvc
public class AppWebConf extends WebMvcConfigurerAdapter {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
return objectMapper;
}
@Bean
public MappingJackson2HttpMessageConverter mappingJacksonMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper());
return converter;
}
@Bean
public Jaxb2RootElementHttpMessageConverter jaxbMessageConverter() {
return new Jaxb2RootElementHttpMessageConverter();
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(jaxbMessageConverter());
converters.add(mappingJacksonMessageConverter());
}
}
爲了測試,我有2種方法的控制器,一個返回一個訂單HTTP GET請求(這一個作品)和一個通過HTTP POST(這一次失敗)接受訂單,例如
@Controller
public class TestController {
@ResponseBody
@RequestMapping(value = "/test", method = RequestMethod.GET)
public Order getTest() {}
@RequestMapping(value = "/test", method = RequestMethod.POST)
public void postTest(@RequestBody order) {}
}
我試過所有關於SO的各種討論的建議,但到目前爲止沒有運氣。任何人都可以發現我做錯了什麼嗎?
這工作!我從'Payment'接口中刪除了'@ JsonSubTypes.Type(name =「creditCardPayment」,value = CreditCardPayment.class),並在'AppWebConf'類中添加了'objectMapper.registerSubtypes(CreditCardPayment.class)'。令人失望的是,註釋不起作用,因爲我想保持我的配置一般,但至少它讓我通過這個問題。謝謝。 – grigori
我面臨同樣的問題,上面的解決方案沒有幫助。 –