I need to create a json from model. But if some field was empty or null in my model my json should not contain that specific key at all.
I need to create a json object like this:
{
"bloodTest": ["640dd3ed11aeebf5200dd319"],
"weight": 100,
"height": 190,
"profile": "640dd41a11aeebf5200dd32b"
}
But for example if weight
field was empty my json object should be like this:
{
"bloodTest": ["640dd3ed11aeebf5200dd319"],
"height": 190,
"profile": "640dd41a11aeebf5200dd32b"
}
I’ve created my json object by this piece of code in my flutter project:
var json = {
"bloodTest": bloodTest ,
"weight": info.weight ,
"height": info.height ,
"profile": info.profile.id ,
}
And if some filed is null or empty it still create the json filed with null or empty value.
How should I fix it?
2
Answers
Dont use static keys in your object
Add for loop onto your infor object which are coming form API and
then get keys and values using entryset
Then get key and with that key get value from json object
If any value come null or empty dont put that key in your local object
If value has any data put key and value in your local object
You can use https://javiercbk.github.io/json_to_dart/ json which you have to convert model paste this page and get model of json. u always use this website. this website gives you correctly