Rapidjson:在文档中添加外部子文档
Rapidjson: add external sub-document to document
我想使用Rapidjson序列化一个嵌套结构到JSON,我也希望能够分别序列化每个对象,所以任何实现ToJson
的类都可以序列化为JSON字符串。
在下面的代码中,Car
有一个Wheel
成员,两个类都实现了方法ToJson
,该方法用它们的所有成员填充rapidjson::Document
。该方法从函数模板ToJsonString
中调用,以获取传递对象的格式化JSON字符串。
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/stringbuffer.h"
template<typename T> std::string ToJsonString(const T &element)
{
rapidjson::StringBuffer jsonBuffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> jsonWriter(jsonBuffer);
rapidjson::Document jsonDocument;
element.ToJson(jsonDocument);
jsonDocument.Accept(jsonWriter);
return jsonBuffer.GetString();
}
struct Wheel
{
std::string brand_;
int32_t diameter_;
void ToJson(rapidjson::Document &jsonDocument) const
{
jsonDocument.SetObject();
jsonDocument.AddMember("brand_", brand_, jsonDocument.GetAllocator());
jsonDocument.AddMember("diameter_", diameter_, jsonDocument.GetAllocator());
}
};
struct Car
{
std::string brand_;
int64_t mileage_;
Wheel wheel_;
void ToJson(rapidjson::Document &jsonDocument) const
{
jsonDocument.SetObject();
jsonDocument.AddMember("brand_", brand_, jsonDocument.GetAllocator());
jsonDocument.AddMember("mileage_", mileage_, jsonDocument.GetAllocator());
rapidjson::Document jsonSubDocument;
wheel_.ToJson(jsonSubDocument);
jsonDocument.AddMember("wheel_", rapidjson::kNullType, jsonDocument.GetAllocator());
jsonDocument["wheel_"].CopyFrom(jsonSubDocument, jsonDocument.GetAllocator());
}
};
如您所见,Car::ToJson
调用Wheel::ToJson
是为了获得Wheel
的描述并将其添加为子对象,但由于分配管理(我也阅读了其他问题),我想不出一个可接受的解决方案来做到这一点。
我发现的解决方案是在Car
的jsonDocument
中添加一个成员,带有一个随机字段值(在本例中为rapidjson::kNullType
),然后在CopyFrom
中添加Wheel
的相应文档。
我该怎么做?
这比我想象的要简单得多。来自GitHub (issue 436):
避免复制的最简单的解决方案是重用外部文档的分配器:
rapidjson::Document jsonSubDocument(&jsonDocument.GetAllocator()); wheel_.ToJson(jsonSubDocument); jsonDocument.AddMember("wheel_", jsonSubDocument, jsonDocument.GetAllocator());
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 如何在文档文件夹中创建目录
- 当Microsoft文档仅包含 C# 示例时,如何查找 C++ 包含文件名
- 通过构造函数创建一些值并尝试添加到文档中使用 rapidjson 不起作用
- 关于类的 Python 文档 - 对C++的引用不正确
- C++/autoconf 等效于文档库要求.txt的要求是什么?
- mbed:使用 USB 文档库编译会导致错误
- C++ VISUAL STUDIO:GLFWwindow没有初始化,即使它是在文档中编写的并且以前工作过
- 使用 yaml-cpp 更新 YAML 文档的节点和值
- 在加载 MSHTML 文档之前从 MSHTML 文档中删除无效的 URL
- 如何在C++中表示JSON文档的递归对象结构?
- 如何查找 Redshift Maya API 文档?
- 如何使用值模板编写文档测试用例?
- 如何使用 Gradle DSL(领域特定语言)上的文档?
- ncurses 找不到任何关于cchar_t的文档
- 提取狮身人面像文档中的C++代码片段
- 关于 API 文档和设备操作 在助手-sdk-cpp 上
- 如何搜索提升文档?
- 使用 mongo c++ 驱动程序查询嵌套的 BSON 文档
- Rapidjson:在文档中添加外部子文档