PaolaJ.
PaolaJ.

Reputation: 11532

How to serialize object to std::string using rapidjson (Implemented serialize)?

How to serialize object to std::string using rapidjson ? I have implemented

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

    }
}

problem is in serialize function what to return ?

Upvotes: 2

Views: 8701

Answers (3)

lafolle
lafolle

Reputation: 99

Question is pretty old, in case you're still looking for answer, then here is the one as suggested by @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();
    }
}

You can also look at example code here: simplewriter.cpp

Upvotes: 4

piokuc
piokuc

Reputation: 26184

Try this:

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

  Serialize(writer);

  return buffer.GetString();
}

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

Nothing. You already sent it to stdout.

If you don't want to stream the output to a file, don't use FileStream; use some other template argument to PrettyWriter, that stores and allows you to extract a string.

From a quick glance through the documentation, StringBuffer looks promising. It's a type alias for GenericStringBuffer<UTF8<> >.

Upvotes: 2

Related Questions