如何使用rapidjson将对象序列化为std :: string? 我已经实施了
class Person{
public:
std::string name;
uint64 id; // uint64 is typedef
template <typename Writer>
void Serialize(Writer& writer) const {
writer.StartObject();
writer.String("name");
writer.String(name);
writer.String(("id"));
writer.Uint64(id);
writer.EndObject();
}
std::string serialize(){
FileStream s(stdout);
PrettyWriter<FileStream> writer(s);
Serialize(writer);
return ? /// There is a problem
}
}
问题是序列化函数要返回什么?
答案 0 :(得分:2)
无。您已将其发送至stdout
。
如果您不想将输出流式传输到文件,请不要使用FileStream
;使用PrettyWriter
的其他模板参数,存储并允许您提取字符串。
通过快速浏览文档,StringBuffer
看起来很有希望。它是GenericStringBuffer<UTF8<> >
的类型别名。
答案 1 :(得分:2)
问题很老,如果你还在寻找答案,那么这里是@Lightness Races in Orbit建议的那个
class Person{
public:
std::string name;
uint64 id; // uint64 is typedef
template <typename Writer>
void Serialize(Writer& writer) const {
writer.StartObject();
writer.String("name");
writer.String(name);
writer.String(("id"));
writer.Uint64(id);
writer.EndObject();
}
std::string serialize(){
StringBuffer s;
Writer<StringBuffer> writer(s);
Serialize(writer);
return s.GetString();
}
}
您还可以在此处查看示例代码:simplewriter.cpp
答案 2 :(得分:0)
试试这个:
std::string serialize() {
GenericStringBuffer<UTF8<> > buffer;
Writer<GenericStringBuffer<UTF8<> > > writer(buffer);
Serialize(writer);
return buffer.GetString();
}