document.Parse
returns null when the JSON you pass in to it is not valid. There is no substitute for creating valid JSON, and that means ensuring that the contents of message
are properly escaped, particularly any "
characters, control characters like line breaks, etc. You have to deal with it, not avoid it.
For example
#include <string>
#include <sstream>
#include <iomanip>
std::string jsonEscape(const std::string &s)
{
std::ostringstream oss;
for(char c : s)
{
switch (c)
{
case '"': oss << "\\\""; break;
case '\\': oss << "\\\\"; break;
case '/': oss << "\\/"; break;
case '\b': oss << "\\b"; break;
case '\f': oss << "\\f"; break;
case '\r': oss << "\\r"; break;
case '\n': oss << "\\n"; break;
case '\t': oss << "\\t"; break;
default:
if ((c >= 0x00) && (c <= 0x1F))
oss << "\\u" << std::hex << std::noshowbase << std::nouppercase << std::setw(4) << std::setfill('0') << (int)c;
else
oss << c;
break;
}
}
return oss.str();
}
std::string temp = "{\"key\": \"" + jsonEscape(message) + "\"}";
Or, you could simply use RapidJSON's own API to produce a valid JSON string, and to parse it afterwards (which would be redundant, since you would already have a Document
):
Document document(kObjectType);
Value key;
key.SetString(StringRef(message.c_str(), message.length()));
document.AddMember("key", key, document.GetAllocator());
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
document.Accept(writer);
std::string temp = buffer.GetString();