write temporary variable to Json : I get \u0000 write temporary variable to Json : I get \u0000 json json

write temporary variable to Json : I get \u0000


The following call:

output.AddMember("test_field",s1.c_str(), allocator);

treats the second parameter as a constant string. This is not OK because s1 will be destroyed out of the block.

You need to make a copy of the string. A solution is:

Value v(s1.c_str(), allocator);output.AddMember("test_field", v, allocator);

Or equivalently:

output.AddMember("test_field", Value(s1.c_str(), allocator).Move(), allocator);

And a faster (also better) version is:

output.AddMember("test_field", Value(s1.c_str(), s1.size(), allocator).Move(), allocator);

Because this does not need to call a strlen()-like function to find the length of s1. And it can handle null character inside a string.


Thanks to Steve I managed to find the answer :

as said in the documentation :"rapidjson provide two strategies for storing string.

  1. copy-string: allocates a buffer, and then copy the source data into it.
  2. const-string: simply store a pointer of string. "

So the right way to do what I wanted is :

rapidjson::Document output;output.SetObject();rapidjson::Document::AllocatorType& allocator = output.GetAllocator();{    std::string s1("test");    rapidjson::Value field;    char buffer[10];    int len = sprintf(buffer, s1); .    field.SetString(buffer, len, allocator);    output.AddMember("test_field",field, allocator);}std::string s2("test");output.AddMember("test_field2",s2.c_str(), allocator);rapidjson::FileStream f(stdout);rapidjson::PrettyWriter<rapidjson::FileStream> writer(f);output.Accept(writer);

The output I get is now :

 {"test_field": "test",   "test_field2": "test"}