I want to create a json string using rapidjson. But I got a error: unable to convert std::string
to rapidjson::Type
.
int x = 111;
string className = "myclass";
Document doc;
auto& allocator = doc.GetAllocator();
doc.AddMember("x", Value().SetInt(x), allocator);
doc.AddMember("className", className, allocator);
unordered_map<string, string>& map = sprite->toMap();
for (const auto& pair : map) {
Value key(pair.first.c_str(), pair.first.size(), allocator);
doc.AddMember(key, pair.second, allocator);
}
StringBuffer sb;
Writer<StringBuffer> writer(sb);
doc.Accept(writer);
log("json string: %s", sb.GetString());
RapidJSON is a JSON parser and generator for C++. It was inspired by RapidXml. RapidJSON is small but complete. It supports both SAX and DOM style API. The SAX parser is only a half thousand lines of code.
In Visual Studio, open the solution and in Solution Explorer, select the project that is using rapidjson and either use the main menu PROJECT Properties function, or right-click on the project and select Properties from the option menu. This will display the Properties dialog.
Document Object Model(DOM) is an in-memory representation of JSON for query and manipulation. The basic usage of DOM is described in Tutorial.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With