Lochana Thenuwara
Lochana Thenuwara

Reputation: 445

How to serialize RapidJSON document to a string?

How to serialize RapidJSON document to a string?
In all the examples the serializing text is redirected to the standard output through the FileStream, but I need to redirect it to a string variable.

Upvotes: 21

Views: 58290

Answers (4)

Simon Pickup
Simon Pickup

Reputation: 892

To avoid having to copy out the string contents, you can create a rapidjson Stream-concept class to wrap an existing std::string, ref: https://github.com/Tencent/rapidjson/issues/846#issuecomment-298088278

In fact, not all the methods implemented there are required. This should do:

void writeDocumentToString(const rapidjson::Document& document,
                           std::string& output)
{
  class StringHolder
  {
  public:
    typedef char Ch;
    StringHolder(std::string& s) : s_(s) { s_.reserve(4096); }
    void Put(char c) { s_.push_back(c); }
    void Flush() { return; }

  private:
    std::string& s_;
  };

  StringHolder os(output);
  rapidjson::Writer<StringHolder> writer(os);
  document.Accept(writer);
}

Upvotes: 2

Lochana Thenuwara
Lochana Thenuwara

Reputation: 445

Example code:

Document document;
const char *json = " { \"x\" : \"0.01\", \"y\" :\"0.02\" , \"z\" : \"0.03\"} ";

document.Parse<0>(json);

//convert document to string

StringBuffer strbuf;
strbuf.Clear();

Writer<StringBuffer> writer(strbuf);
document.Accept(writer);

std::string ownShipRadarString = strbuf.GetString();
std::cout << "**********************************************" << ownShipRadarString << std::endl;

Upvotes: 5

Milo Yip
Milo Yip

Reputation: 5072

In the first page of the project, the code already shows how to serialize a document into a string (stringify a document):

// 3. Stringify the DOM
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);

// Output {"project":"rapidjson","stars":11}
std::cout << buffer.GetString() << std::endl;

buffer.GetString() here returns a string of const char* type. It also has a buffer.GetSize() for returning the size of output string. So, if you would convert it to a std::string, the best way is:

std::string s(buffer.GetString(), buffer.GetSize());

The tutorial.cpp also show the same thing, in addition to other common usage of RapidJSON.

Upvotes: 20

A.Franzen
A.Franzen

Reputation: 745

Like this:

const char *GetJsonText()
{
  rapidjson::StringBuffer buffer;

  buffer.Clear();

  rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
  doc.Accept(writer);

  return strdup( buffer.GetString() );
}

Then of couse you have to call free() on the return, or do:

return string( buffer.GetString() );

instead.

Upvotes: 19

Related Questions