就我個人而言,我更喜歡在編寫器中允許在寫入時過濾掉空/空屬性的選項。因此,可以定義像class MyFastWriter : public FastWriter
這樣的自己的類,相應地替代printValue
來處理類型objectValue
,並且其餘的請求FastWriter::writeValue
。不幸的是,JsonCpp API已經將成員函數printValue
定義爲私有的,因此您無法從自定義派生類中覆蓋它(甚至不會調用它)。 (1)在寫入之前調整json值,(2)定義一個自己的作家類並從FastWriter
複製很多代碼,或者(3)更改源代碼爲FastWriter
。
Jarod提供的選項(1)已經有了正確的答案。選項(2)和(3)共享主要缺點,即您複製或更改可能在JsonCpp未來版本中更改的實現細節;但是,如果人們非常清楚改變或複製圖書館的源代碼所帶來的弊端,它可能是一種選擇。一種情況可能是,手頭的json值應該保持空的屬性,非常大,必須經常寫;那麼複製這個值就變得很不方便,改變它只是爲了寫,然後一次又一次地寫。
我當然不是改變源代碼的朋友;無論如何,看到FastWriter::writeValue
以下改編版本,實現了輸出你想要的:
void FastWriter::writeValue(const Value& value) {
switch (value.type()) {
// cases handling the other value.types remain as is...
...
// case handling objectValue is adapted:
case objectValue: {
Value::Members members(value.getMemberNames());
document_ += '{';
// inserted flag indicating that the first element is to be written:
bool isFirst = true;
for (Value::Members::iterator it = members.begin(); it != members.end();
++it) {
const std::string& name = *it;
// inserted to skip empty/null property values
if(value[name].empty() || value[name].isNull())
continue;
// Replaced: necessary because the first written entry is not necessarily members.begin:
// if (it != members.begin())
// document_ += ',';
if (!isFirst)
document_ += ',';
else
isFirst = false;
// Kept as is...
document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length()));
document_ += yamlCompatiblityEnabled_ ? ": " : ":";
writeValue(value[name]);
}
document_ += '}';
} break;
}
}
'sed'/:\ W * null \ W *,/ d''? – YSC