2

How do I get the entire rapidjson::Document as a string?

I've got the following code:

rapidjson::Document jsonDoc;
rapidjson::MemoryPoolAllocator<> & allocator = jsonDoc.GetAllocator();
jsonDoc.SetObject();
jsonDoc.AddMember("ACTION", "poop", allocator);
jsonDoc.AddMember("TRANSACTIONID", 2, allocator);
std::string json = jsonDoc.GetString(); // Assert fails here, not a string

and it fails an assert, because it is not a string.

I've seen some examples where people use SAX rather than DOM to get string using:

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

writer.StartObject();

writer.String("ACTION");
writer.String("poop");

writer.String("Trans");
writer.Int(19);

writer.EndObject();

std::string json = buffer.GetString();

But I'd rather build my DOM the former way and not use SAX.


EDIT:

Reading the documentation some more, it would appear they want us to use SAX to convert a DOM to a string? From the following:

"DOM as SAX Event Publisher

In RapidJSON, stringifying a DOM with Writer may be look a little bit weired. // ... Writer writer(buffer); d.Accept(writer);

Actually, Value::Accept() is responsible for publishing SAX events about the value to the handler. With this design, Value and Writer are decoupled. Value can generate SAX events, and Writer can handle those events.

User may create custom handlers for transforming the DOM into other formats. For example, a handler which converts the DOM into XML.

For more about SAX events and handler, please refer to SAX. "

So, I've come up with the following code. Can someone verify this is the way to do it?

std::string myString1("poop");
const std::string myString2("poopy");

rapidjson::Document jsonDoc;
rapidjson::MemoryPoolAllocator<> & allocator = jsonDoc.GetAllocator();

jsonDoc.SetObject();

// We have to use StringRef because they can't handle an std::string, WTF?
jsonDoc.AddMember("ACTION", rapidjson::StringRef(myString1.c_str()), allocator);
jsonDoc.AddMember("CONSTACTION", rapidjson::StringRef(myString2.c_str()), allocator);
jsonDoc.AddMember("TRANSACTIONID", 2, allocator);

rapidjson::StringBuffer buffer;
buffer.Clear();
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
jsonDoc.Accept(writer);
std::string json = buffer.GetString();
Christopher Pisz
  • 3,757
  • 4
  • 29
  • 65

0 Answers0