1

I want to remove the Null and Empty values from my JSON Response.

Below is Json String:

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

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

}

in this case : productSpecPricing with childPricingSchema

What will be best approach to remove empty objects which will be generic for any JSON String.

0

2 Answers 2

2

Using Jackson you can easy set your preferences to serialize your objects

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));

I got this:

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

as productSpecPricing isn't null (or empty array/collection) it's shown, to solve it you have to add a filter:

annotate the class that contains the productSpecPricing property with @JsonFilter("myFilter")

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

Filter:

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;
    }
};

after apply the filter the result is:

{
  "implDisplayablePricePlan" : [ {
    "assignedPricePlanID" : "abc",
    "name" : "GOLD",
    "action" : "Something",
    "status" : "Something",
    "selected" : true,
    "crossProductDiscount" : false,
    "displayInformation" : {
      "visible" : true,
      "enalble" : false
    }
  } ]
}
Sign up to request clarification or add additional context in comments.

5 Comments

I have REST classes which are configured using @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) So i am looking for capturing the JSON in the Reponse Body and remove all the null or empty values. I am new to REST and Springs so probably some thing might be lost in translation. Any help will be appreciated.
... so you are not the one generating that json?, you are using Spring?, you should give revelant info in your question
I am using @Path("/somepath") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) at the top of my interfaceclass which is generating Json reponse...
This even works with Spring as it typically uses Jackson. You have to configure the message converter (see MappingJackson2MessageConverter.setObjectMapper())
yes, but I had proposed extend the ObjectMapper to add the settings and set it as message converter
0

It depends on how you are getting/creating the JSON file.

If you are creating it, then, during creation, if a value is non-existant, null, void or any other you do not desire, do not insert it.

However, if you are receiving this JSON from others, then during parse, get the key/pair value, again, if you do not want it, do not add to your object.

Without details from your program, we cant help further

Edit 1:

This code in PHP is (adapted from the one I use):

$input = file_get_contents($name, "r");
if($input != FALSE) {
    for($i=0;$i<strlen($input);$i++){
        if($input[$i]=='{'){
            $begin= $i;
        } else if($input[$i]=='}'){
            $buffer .= substr($input,$begin,$i-$begin+1) .",";
            if (strpos($buffer,'":null') !== false) {
                // Drop the current line
            } else {
                // Line is correct, keep on writting
            }
            if($counter>=100 ){
                $counter= 0;
                save($buffer);
                $buffer = "";
            }
        } else if($input[$i]==']'){
            save($buffer);
            $buffer = "";
            $i = strlen($input);
        }
    }


}

In it, we will first successfully get the JSON file. Then, open the file, read each "section" (or object) of a JSON structure, then do as we must (in my case, I would fix the input, but I guess you can just drop it.)

8 Comments

I am having REST(with Spring) services which produces JSON. so when it is displayed it is showing empty objects. I want to remove empty objects before it is displayed as JSON in REST service. Using Object Mapper in Spring xml is also not working. I hope there is generic way to go about this for any REST call.
Then how about reading the input as a file, iterating the content, and check after ":null and ":""?
This isjust tip of iceberg. file is huge.
Yes, but you are receiving the file anyway, and as far as I know, most systems will read JSONs as a single input (and load it completely on RAM)
is it possible. could you please help me with it cause i tried readTree functionality and it didn't work. Some sample example will do the trick
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.