我有一个对象doc
,它有自己的反序列化器注释,即
@JsonSerialize(using = DocDeSerializer.class)
public class Doc {
,反序列化器看起来像
@Service
public class DocDeserializer<T> extends JsonDeserializer<Doc> i{
@Autowired
private PropertyController ctrlProp;
@Override
public Doc deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
...
HTTP请求的完整反序列化工作正常。但现在我遇到了将String转换为doc
的挑战。我的方法
final ObjectMapper objectMapper = new ObjectMapper();
final Doc myDoc = objectMapper.readValue(strContent, Doc.class);
失败。原因是未正确启动自动装配的类,即未启动ctrlProp
(= null
)。所以,我的问题是:
是否有一种简单的方法可以重用Spring中的Deserializer?如果是这样,怎么样?
更新
经过调查,我发现它与HttpConverts的配置有关。所以我的配置看起来像:
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
@Primary
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
converter.setObjectMapper(builder.build());
return converter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
....
converters.add(mappingJackson2HttpMessageConverter());
}
}
用于
@RestController
public class MyClass
@Autowired
private MappingJackson2HttpMessageConverter myJackson;
但不知怎的,这也失败了:-(只是为了清楚起见,尝试了......