如何即时修改嵌套的 rapidjson 对象?

How to modify nested rapidjson object on the fly?

我能找到的所有具有嵌套对象的 rapidjson 示例基本上如下所示: 1)创建根对象 2)创建嵌套对象 3) build/add 到嵌套对象(根对象至今未改变) 4) 嵌套对象完成后,添加到根对象

我想在更高层次上做的事情: 1)创建根对象 2)创建嵌套对象并添加到根对象 3) build/add 到嵌套对象(根对象本身也会更新,无需进一步操作)

这样一来,如果在构建嵌套对象时抛出异常,将其添加到根对象的步骤已经完成,所以我至少部分构建了嵌套对象,而不是完全缺失。

这可能吗?任何帮助或见解将不胜感激!

我想通了;但是,由于我没有找到支持它的文档,我不确定我是否真的依赖于任何未定义或不受支持的行为。

//Prepare 'root' object as a document
rapidjson::Document document;
rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
document.SetObject();
// 'document' currently serializes to {}

//Create an empty rapidjson 'object' as a Value, and add it to root
rapidjson::Value nestedObject(rapidjson::kObjectType);
document.AddMember("Parent", nestedObject, allocator);
// 'document' currently serializes to {"Parent":{}}

/*Retrieve the 'object' as a Value
This step is important! Trying to reuse the same 'nestedObject' Value from before
without "re-retrieving" it will result in assertion errors at runtime.
If you try to "re-retrieve" into the existing 'nestedValue' instance, the end
result below will be {"Parent":null}*/
rapidjson::Value &nestedObjectValue = document["Parent"];

//Modify the 'nestedObjectValue'
nestedObjectValue.AddMember("child", "child_value", allocator);
// 'document' currently serializes to {"Parent":{"child":"child_value"}}

最终,这是我想要的行为。我可以访问嵌套对象并可以随意修改它,并且更改会影响根文档。