我知道这些注释@JsonInclude(JsonInclude.Include.NON_NULL)和@JsonInclude(JsonInclude.Include.EMPTY),但在我的情况下不起作用。

我的情况是:

我有一些类(实体(SomeClass))和其他实体(SomeObject)

    @Data
    public class SomeClass {
        private String fieldOne;
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private String fieldTwo;
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private SomeObject someObject;
    }


实体-SomeObject

@Data
public class SomeObject {
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String name;
}


主班

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        SomeClass someClass = new SomeClass();
        someClass.setFieldOne("some data");

        SomeObject someObject = new SomeObject();
        someObject.setName(null);
        someClass.setSomeObject(someObject);

        ObjectMapper objectMapper = new ObjectMapper();
        String someClassDeserialized = objectMapper.writeValueAsString(someClass);
        System.out.println(someClassDeserialized);
    }
}


输出量

{"fieldOne":"some data","someObject":{}}


最终输出应为不包含空字段或空字段的对象(SomeObject):

{"fieldOne":"some data"}

最佳答案

我认为只能在此处应用自定义逻辑。您需要使用@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = YourFilter.class)并创建自定义YourFilter类。您可以使用boolean方法创建基本接口,并在所有需要根据该类中所有/所需字段的空性将其过滤掉的类中重写它。
或者,您可以在此方法中解析@JsonInclude(JsonInclude.Include.NON_NULL)批注,以获取所有字段,您需要检查这些字段是否为空。

https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html

10-08 14:27