根据Google JSON样式指南,建议删除空值或空值.
使用JsonCpp时,如何从对象结构或写入流中删除空值或空值?
我想要以下代码:
#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;
Run Code Online (Sandbox Code Playgroud)
生产:
{
"id": 4,
}
Run Code Online (Sandbox Code Playgroud)
您可以添加一个预处理来删除空成员,例如:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
最后:
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1084 次 |
| 最近记录: |