gpt4 book ai didi

java - 从 JSON 响应(Spring REST)中删除空对象和空对象,空对象内有空对象

转载 作者:行者123 更新时间:2023-11-30 03:13:39 25 4
gpt4 key购买 nike

我想从 JSON 响应中删除 Null 和 Empty 值。

下面是 Json 字符串:

{"implDisplayablePricePlan": [
{
"productSpecPricing": {
"childPricingSchema": {}
},
"assignedPricePlanID": "abc",
"name": "GOLD",
"action": "Something",
"status": "Something",
"selected": true,
"crossProductDiscount": false,

"displayInformation": {
"visible": true,
"enabled": false
}
}]

}

在本例中:productSpecPricing 与 childPricingSchema

删除对于任何 JSON 字符串通用的空对象的最佳方法是什么。

最佳答案

使用Jackson您可以轻松设置首选项来序列化对象

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.setSerializationInclusion(Include.NON_EMPTY);
ObjectWriter writer = objectMapper.writer();
System.out.println(writer.writeValueAsString(YOUR_OBJECT));

我得到了这个:

{
"implDisplayablePricePlan" : [ {
"productSpecPricing" : { },
"assignedPricePlanID" : "abc",
"name" : "GOLD",
"action" : "Something",
"status" : "Something",
"selected" : true,
"crossProductDiscount" : false,
"displayInformation" : {
"visible" : true,
"enalble" : false
}
} ]
}

因为 productSpecPricing 不为 null(或空数组/集合),所以要解决这个问题,您必须添加一个过滤器:

使用 @JsonFilter("myFilter") 注释包含 productSpecPricing 属性的类

FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", filter);
ObjectWriter writer = objectMapper.writer(filters);

过滤器:

PropertyFilter filter = new SimpleBeanPropertyFilter() {

@Override
public void serializeAsField(Object pojo, JsonGenerator jgen,
SerializerProvider provider, PropertyWriter writer)
throws Exception {
if (include(writer)) {
System.out.println(writer.getName());
if (!writer.getName().equals("productSpecPricing")) {
writer.serializeAsField(pojo, jgen, provider);
return;
} else {
ProductSpecPricing productSpecPricing = ((YOU_OBJECT) pojo).getProductSpecPricing();
if (productSpecPricing != null && productSpecPricing.getChildPricingSchema() != null && !productSpecPricing.getChildPricingSchema().isEmpty()) {
writer.serializeAsField(pojo, jgen, provider);
}
}
} else if (!jgen.canOmitFields()) {
writer.serializeAsOmittedField(pojo, jgen, provider);
}
}

@Override
protected boolean include(PropertyWriter writer) {
return true;
}

@Override
protected boolean include(BeanPropertyWriter writer) {
return true;
}
};

应用过滤器后的结果是:

{
"implDisplayablePricePlan" : [ {
"assignedPricePlanID" : "abc",
"name" : "GOLD",
"action" : "Something",
"status" : "Something",
"selected" : true,
"crossProductDiscount" : false,
"displayInformation" : {
"visible" : true,
"enalble" : false
}
} ]
}

关于java - 从 JSON 响应(Spring REST)中删除空对象和空对象,空对象内有空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33131108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com