延迟对象在Jackson ObjectMapper中未转换为null

时间:2014-01-22 02:40:50

标签: java spring hibernate jackson

我使用Spring 3.1.4和jackson-datatype-hibernate 2.2.3并从我的REST-Service开始从JPA获取我的User-Object。所以现在邮件被自动取出了懒惰。我想要的是一个名称和邮件的JSON只是空。

MyRest方法:

@Transactional(readOnly = true)
@RequestMapping(
        value="/get/{userId}", 
        method = RequestMethod.GET,
        produces={"application/json","application/xml"}
        )
@ResponseBody
public User getUser(@PathVariable("userId") Long userId){
    User result = userManager.getUser(userId);
    return result;
}

最小化用户类:

public class User{

    private String name;

    @OneToMany
    private Set<Mail> mails;
}

Custom Jackson Object Mapper:

public class CustomJacksonObjectMapper extends ObjectMapper {

public CustomJacksonObjectMapper() {
    super();
    this.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
    this.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
    this.setSerializationInclusion(Include.NON_NULL);
}

}

初始化
@Configuration
@ComponentScan(basePackages = { "com.fabel" })
public class SpringConfiguration extends WebMvcConfigurationSupport{

 @Bean
  public ObjectMapper objectMapper() {
        CustomJacksonObjectMapper objectMapper = new CustomJacksonObjectMapper();
    Hibernate4Module hibernate4Module = new Hibernate4Module();
    objectMapper.registerModule(hibernate4Module);
    return objectMapper;
  }

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    MappingJackson2HttpMessageConverter converter = new                               MappingJackson2HttpMessageConverter();
   converter.setObjectMapper(objectMapper());
   converters.add(converter);
  }

}

我将我的实施定位在德国博客http://blog.rasc.ch/?p=2441上并做了所有提到的事情。 任何想法我能做什么? @JacksonIgnore是没有选择的,因为有时我需要发送惰性对象。然后我会简单地使用Hibernate.initialize。我错过了什么?

1 个答案:

答案 0 :(得分:0)

这可能为时已晚,无论如何,有一个库可以帮助您通过hiberante延迟加载jackson-datatype-hibernate4

您可以按照以下步骤创建一个ObjectMapper对象,该对象可以加载延迟数据并对其进行序列化:

ObjectMapper mapper = new ObjectMapper();
Hibernate4Module hibernate4Module = new Hibernate4Module();
hibernate4Module.enable(Hibernate4Module.Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS);
mapper.registerModule(hibernate4Module);