简体   繁体   中英

Filter Empty Objects in jackson ArrayNode class while serialization

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM