// in header
class CJSONUtils
{
public:
static Json::Value HidePrivateData(const Json::Value& value,
const std::vector<std::string>& pathSufixes);
private:
static void ShadowPrivateData(Json::Value& value,
const std::vector<std::string>& pathSufixes,
const std::string& sPath);
static bool IsPrivatePath(const std::string& sPath,
const std::vector<std::string>& pathSufixes);
static std::string MaskPrivateText(const std::string& sPrivateText);
};
// in cpp
#include "JSONUtils.h"
#include "StringUtils.h"
#include <algorithm>
#include <json/json.h>
using namespace std;
using namespace Json;
Value CJSONUtils::HidePrivateData(const Value& value,
const vector<string>& pathSufixes)
{
Value result { value };
ShadowPrivateData(result, pathSufixes, {});
return result;
}
void CJSONUtils::ShadowPrivateData(Value& value,
const vector<string>& pathSufixes,
const string& sPath)
{
switch (value.type())
{
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
break;
case stringValue:
if (IsPrivatePath(sPath, pathSufixes))
{
value = Value { MaskPrivateText(value.asString()) };
}
break;
case arrayValue:
for (auto& arrayValue : value)
{
ShadowPrivateData(arrayValue, pathSufixes, sPath + "[]");
}
break;
case objectValue:
for (auto it = value.begin(); it != value.end(); ++it)
{
ShadowPrivateData(*it, pathSufixes, sPath + "." + it.key().asString());
}
break;
}
}
bool CJSONUtils::IsPrivatePath(const string& sPath,
const vector<string>& pathSufixes)
{
return std::any_of(pathSufixes.begin(),
pathSufixes.end(),
[&](const string& sSufix)
{
return EndsWith(sPath, sSufix);
});
}
std::string CJSONUtils::MaskPrivateText(const std::string& sPrivateText)
{
if (sPrivateText.length() < 15)
{
return std::string(sPrivateText.length(), '*');
}
ostringstream result;
result << "< *" << sPrivateText.length() << " characters * >";
return result.str();
}
从现在起
Json::Value
LOG() << " JSON received: " << CJSONUtils::HidePrivateData(jsonRoot, listOfPrivateItemsPaths);
我已经为它编写了测试(gtest),它工作起来很有魅力。