我想使用 Rapidjson 将嵌套结构序列化为 JSON,并且我还希望能够单独序列化每个对象,因此任何实现的类ToJson
都可以序列化为 JSON 字符串。
在下面的代码中,Car
有一个Wheel
成员,两个类都实现了 method ToJson
,它用它们的所有成员填充 a 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
's中添加一个jsonDocument
具有随机字段值的成员(在本例中rapidjson::kNullType
),然后将其添加到CopyFrom
' Wheel
s 的相应文档中。
我怎样才能做到这一点?