Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add string pairs to a document of rapidjson

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());
like image 971
Zen Avatar asked Jan 03 '16 06:01

Zen


People also ask

What is RapidJSON C++?

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.

How do I use RapidJSON in Visual Studio?

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.

What is Dom JSON?

Document Object Model(DOM) is an in-memory representation of JSON for query and manipulation. The basic usage of DOM is described in Tutorial.


1 Answers

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...

like image 192
Milo Yip Avatar answered Sep 16 '22 19:09

Milo Yip