c++rapidjson

Return null or empty Document in rapidjson


I've created a helper method that parses a char *. But when something fails I want it to return a null like Document. How would I do this for rapidjson? For example, In jsoncpp they had Value::null.

Document & CEJsonHelper::parse(const char * inputString) {
    Document d;
    auto& document = d.Parse(inputString);

    if(document.HasParseError()){
        auto error = "Failed to parse JSON (offset " + std::to_string(d.GetErrorOffset()) + "). "
                "Error: " + GetParseError_En(document.GetParseError());
        Log(error);
        return Document::Null; //wrong
    }

    return document;
}

Solution

  • As far as I understand the request, you can change the last line to

    return d.Parse("{}");
    

    If this code is possibly frequent and the returned document is not intended to be changed (in this case you better change the return value of the function to const Document&), you might want to cache the result of the abovementioned expression somewhere in your application, and return it as needed.

    UPDATE: also, I might be wrong, but later versions of RapidJson (at least current stable 1.1.0) throw an exception on bad document instead of flagging an error variable.