[英]How to tell Jackson to ignore a Object with EMPTY or NULL fields during serialization?
I know about these annotations @JsonInclude(JsonInclude.Include.NON_NULL) and @JsonInclude(JsonInclude.Include.EMPTY) but in my case it's doesn't work.我知道这些注释 @JsonInclude(JsonInclude.Include.NON_NULL) 和 @JsonInclude(JsonInclude.Include.EMPTY) 但在我的情况下它不起作用。
My case is:我的情况是:
I have some class (entity (SomeClass)) with some other entity inside (SomeObject)我有一些 class (实体(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;
}
Entity - SomeObject实体 - SomeObject
@Data
public class SomeObject {
@JsonInclude(JsonInclude.Include.NON_NULL)
private String name;
}
Main class主class
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);
}
}
Output Output
{"fieldOne":"some data","someObject":{}}
The final output should be, without object (SomeObject) with null or empty fields:最终的 output 应该是,没有 object (SomeObject) 和 null 或空字段:
{"fieldOne":"some data"}
I think only custom logic can be applied here.我认为这里只能应用自定义逻辑。 You need to use @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = YourFilter.class)
and create custom YourFilter
class.您需要使用@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = YourFilter.class)
并创建自定义YourFilter
class。 You can create base interface with boolean method, and override it in all classes which needs to be filtered out based on nullability of all/desired fields in the class.您可以使用 boolean 方法创建基本接口,并在所有需要根据 class 中所有/所需字段的可空性过滤掉的类中覆盖它。 Or you can parse @JsonInclude(JsonInclude.Include.NON_NULL)
annotations in this method, to get all fields, which nullability you need to check.或者您可以在此方法中解析@JsonInclude(JsonInclude.Include.NON_NULL)
注释,以获取所有字段,您需要检查哪些可空性。
https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.