Filter Empty Objects in jackson ArrayNode class while serialization

Viewed 19

I have a Json:

{  
   "field":[  
      {  
         "key":"123",
         "name":"book1"
      },
      {}
   ]
}

I want to serialize this json to string but in the serialized string i don't want the empty object : "{}".

I need to remove the empty object in the above array node of the json when i am writing jackson JsonNode class to String.

One solution is to iterate the JsonNode beforehand and remove the empty node manually. But i want this empty object to be removed when jackson writes this array node to string. I just want to know if this is possible. Is it possible to override the serialize function of ArrayNode class?

1 Answers

Try this

const array = {  
   "field":[  
      {  
         "key":"123",
         "name":"book1"
      },
      {}
   ]
}
const filteredArray = array.field.filter(arr => arr.key);
const stringArray = JSON.stringfy(filteredArray);
console.log(stringArray);
Related