1

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 Answer 1

0

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);
Sign up to request clarification or add additional context in comments.

2 Comments

in this you are also traversing the array beforeahnd and filtering it before JSON.stringify which increases some computation. I want this to be done somehow internally in JSON.stringify.
Any way you do, you have to filter the array!!

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.