我所能找到的具有嵌套对象的rapidjson的所有示例本质上如下: 1)创建根对象2)创建嵌套对象3)构建/添加到嵌套对象(根对象到目前为止没有改变) 4)一旦嵌套对象完成,就添加到根对象
我想在高层次上做的是: 1)创建根对象2)创建嵌套对象并添加到根对象3)构建/添加到嵌套对象(根对象本身也会更新,不需要进一步的操作)
这是因为,如果在构建嵌套对象时抛出异常,则将其添加到根对象的步骤已经完成,因此我至少部分地构建了嵌套对象,而不是完全丢失。
这个是可能的吗?任何帮助或见解都将不胜感激!
发布于 2019-02-27 12:42:50
我能够弄清楚这一点;但是,由于我还没有找到支持它的文档,我不确定我是否真的依赖于任何未定义或不受支持的行为。
//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"}}最终,这是我想要的行为。我可以访问嵌套的对象,并可以随意修改它,这些更改将影响根文档。
https://stackoverflow.com/questions/54878626
复制相似问题