How can I add string pairs to a document of rapidjson
If #define RAPIDJSON_HAS_STDSTRING 1
(before including rapidjson header files, or defined in compiling flags), there are some extra APIs for std::string
.
To make "copy-strings" (allocated duplicates of source strings) of std::string
, you can use constructor with allocator:
for (auto& pair : map) { rapidjson::Value key(pair.first, allocator); rapidjson::Value value(pair.second, allocator); doc.AddMember(key, value, allocator);}
Or make it a single statement:
for (auto& pair : map) doc.AddMember( rapidjson::Value(pair.first, allocator).Move(), rapidjson::Value(pair.second, allocator).Move(), allocator);
If you presume that the lifetime of strings are longer than doc
, then you can use "const-string" instead, which is simpler and more efficient:
for (auto& pair : map) doc.AddMember( rapidjson::StringRef(pair.first), rapidjson::StringRef(pair.second), allocator);
I think the macro RAPIDJSON_HAS_STDSTRING
should be documented better...
Now, I realise that I have made 2 mistake:
1. I should invoke doc.SetObject();
after doc
is created.
2. How to create string in rapidjson.
Document doc;doc.SetObject();auto& allocator = doc.GetAllocator();rapidjson::Value s;s = StringRef(className.c_str());doc.AddMember("className", s, allocator);auto& map = sprite->toJson();for (auto& pair : map) { rapidjson::Value key(pair.first.c_str(), pair.first.size(), allocator); rapidjson::Value value(pair.second.c_str(), pair.second.size(), allocator); doc.AddMember(key, value, allocator);}
There should be some better way to do it.