2

如何使用 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

    }
}

问题在于序列化函数要返回什么?

4

3 回答 3

4

问题已经很老了,如果您仍在寻找答案,那么这是@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

于 2014-11-11T12:01:49.353 回答
2

没有什么。您已经将它发送到stdout

如果您不想将输出流式传输到文件,请不要使用FileStream; 使用其他一些模板参数来PrettyWriter存储并允许您提取字符串。

快速浏览一下文档,StringBuffer看起来很有希望。它是GenericStringBuffer<UTF8<> >.

于 2013-02-02T11:32:20.067 回答
0

尝试这个:

std::string serialize() {
  GenericStringBuffer<UTF8<> > buffer;
  Writer<GenericStringBuffer<UTF8<> > > writer(buffer);

  Serialize(writer);

  return buffer.GetString();
}
于 2013-02-02T11:32:48.473 回答