According to the Google JSON style guide, it is advisable to remove empty or null values.
When using JsonCpp, how can empty or null values be removed, either from the object structure or when writing to a stream?
I want the following code:
#include <json/json.h>
#include <json/writer.h>
Json::Value json;
json["id"] = 4;
// The "name" property is an empty array.
json["name"] = Json::Value(Json::arrayValue);
Json::FastWriter fw;
std::cout << fw.write(json) << std::endl;
to produce:
{
"id": 4,
}
In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.
Just use this @JsonSerialize(include = Inclusion. NON_NULL) instead of @JsonInclude(Include. NON_NULL) and it works..!! NOTE : com.
In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.
You may add a pre-process to remove empty members, something like:
void RemoveNullMember(Json::Value& node)
{
switch (node.type())
{
case Json::ValueType::nullValue: return;
case Json::ValueType::intValue: return;
case Json::ValueType::uintValue: return;
case Json::ValueType::realValue: return;
case Json::ValueType::stringValue: return;
case Json::ValueType::booleanValue: return;
case Json::ValueType::arrayValue:
{
for (auto &child : node)
{
RemoveNullMember(child);
}
return;
}
case Json::ValueType::objectValue:
{
for (const auto& key : node.getMemberNames())
{
auto& child = node[key]
if (child.empty()) // Possibly restrict to any of
// nullValue, arrayValue, objectValue
{
node.removeMember(key);
}
else
{
RemoveNullMember(node[key]);
}
}
return;
}
}
}
And so finally:
Json::Value json;
json["id"] = 4;
json["name"] = Json::Value(Json::arrayValue); // The "name" property is an empty array.
RemoveNullMember(json); // Or make a copy before.
Json::FastWriter fw;
std::cout << fw.write(json) << std::endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With