如何在Spring Hibernate项目的JSON Jackson中忽略“ handler”:{},“ hibernateLazyInitializer”:{}?

6 java spring json hibernate jackson

我在对象映射器中使用fasterxml 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);
        }
Run Code Online (Sandbox Code Playgroud)

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

"listing": {
          "listingId": 1,
          "name": "Business",
          "handler": {},
          "hibernateLazyInitializer": {}
        },
        "handler": {},
        "hibernateLazyInitializer": {}
      },
Run Code Online (Sandbox Code Playgroud)

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

我尝试了以下解决方案:

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Run Code Online (Sandbox Code Playgroud)

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

ala*_*ive 14

您可以尝试在 Object.class 中添加一个 mixin:

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

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private abstract class IgnoreHibernatePropertiesInJackson{ }
Run Code Online (Sandbox Code Playgroud)


小智 6

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

objectMapper.registerModule(
    new Hibernate4Module().configure(
        Hibernate4Module.Feature.FORCE_LAZY_LOADING, true));
Run Code Online (Sandbox Code Playgroud)


sha*_*zin 1

似乎"handler": {}, "hibernateLazyInitializer": {}属性似乎为空或为空。您可以使用以下配置来忽略空或 null 属性。

mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
Run Code Online (Sandbox Code Playgroud)

或者,如果您有权访问类注释handlerhibernateLazyInitializer@JsonIgnore将阻止它在全局范围内序列化。