如何忽略“handler”: {}, “hibernateLazyInitializer”: {} in json jackson in Spring hibernate project?

2022-09-03 13:18:31

我正在使用更快的xml json和对象映射器,下面是我的代码:

 ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        try {
            String jsonInString = mapper.writeValueAsString(myClassObjectHere);
            return new ResponseEntity<String>(jsonInString, HttpStatus.OK);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
        }

我已经实现并使用代码的方式,我得到了所需的输出,但json在某些json对象中有2个随机的奇怪值,如下所示:

"listing": {
          "listingId": 1,
          "name": "Business",
          "handler": {},
          "hibernateLazyInitializer": {}
        },
        "handler": {},
        "hibernateLazyInitializer": {}
      },

如何配置objectmappper以忽略输出的json中的值?"handler": {}, "hibernateLazyInitializer": {}

我尝试了以下解决方案:

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

但它不起作用,输出仍然与我上面发布的相同。另外,我知道我可以通过注释类来忽略这些处理程序并在json中休眠LazyInitializer,但是有没有办法全局配置json jackson对象映射器,以便它永远不会在我输出的json中添加这些值?@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})


答案 1

您可以尝试将 mixin 添加到 Object.class:

public ObjectMapper getObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(Object.class, IgnoreHibernatePropertiesInJackson.class);
    return mapper;
}

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private abstract class IgnoreHibernatePropertiesInJackson{ }

答案 2

我刚刚遇到了同样的问题,并找到了一种方法,通过将Hibernate4Module添加到映射器来全局正确映射休眠实体:

objectMapper.registerModule(
    new Hibernate4Module().configure(
        Hibernate4Module.Feature.FORCE_LAZY_LOADING, true));