Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore null objects when writing JSON with JsonCpp

Tags:

c++

json

jsoncpp

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,
}
like image 293
Kevin Avatar asked Feb 27 '17 22:02

Kevin


People also ask

How do I ignore null values in JSON object?

In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.

How do I ignore null values in post request body in spring boot?

Just use this @JsonSerialize(include = Inclusion. NON_NULL) instead of @JsonInclude(Include. NON_NULL) and it works..!! NOTE : com.

How do I ignore null values in Jackson?

In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.


1 Answers

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;
like image 174
Jarod42 Avatar answered Sep 28 '22 04:09

Jarod42