从方法返回JsonDoc作为引用

时间:2019-02-19 13:35:47

标签: c++ json rapidjson

我有以下方法给出一个jsonDoc作为参考

bool MyClass::jsonTest(rapidjson::Document & rjsonDoc)
{
    rjsonDoc.SetObject();
    rapidjson::Value val(rapidjson::kObjectType);
    val.AddMember("a", 1, rjsonDoc.GetAllocator());
    val.AddMember("b", 2, rjsonDoc.GetAllocator());
    val.AddMember("c", 3, rjsonDoc.GetAllocator());
    rjsonDoc.AddMember("Values", val, rjsonDoc.GetAllocator());

    //outputs the json into a file
    std::FILE* fp = fopen("outputjsonTest.json", "wb"); // non-Windows use "w"
    char writeBuffer[65536];
    rapidjson::FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
    rapidjson::Writer<rapidjson::FileWriteStream> writer(os);
    rjsonDoc.Accept(writer);
    fclose(fp);

    return false;
}

上述方法在调用时会将完美的json写入文件outputjsonTest.json

但是在另一个类中调用该方法并将其写入文件后,

rapidjson::Document d;
CData_BisconaCtrl dMan;
dMan.jsonTest(d);
//outputs the json into a file
        std::FILE* fp = fopen("outputruntest.json", "wb"); // non-Windows use "w"
char writeBuffer[65536];
rapidjson::FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
rapidjson::Writer<rapidjson::FileWriteStream> writer(os);
d.Accept(writer);
fclose(fp);

outputruntest.json文件为空。

似乎我不能使用按引用传递样式来从方法返回jsonDocument。还是我做错了?完全可以通过这种方式返回jsonDocument吗?

1 个答案:

答案 0 :(得分:0)

我认为您的所作所为没有错。而且,我尝试运行您的代码,它似乎对我有用。

也就是说,您应该注意,如果尝试多次使用Writer(例如,要打印多个文档或第二次打印相同的文档),则需要{ {1}},首先。它将在第一个文档的末尾停止产生输出,因此,如果您尝试打印第二个文档,它将不会产生任何输出(因为结果将不是合法的JSON“文档”)。

[编辑:] 但是,您可以尝试查询它以查看其中的内容,而不是将对象转储到文件中。检查其类型,大小,容量;查看它是否具有预期的成员,或遍历其成员/条目;等等。所有这些都失败了,我将尝试证明基本的C ++东西正在工作。 (即:实际上正在调用正确的方法吗?是否正在处理任何意外的异常?该方法是否接收到您要发送的对象?等等)

祝你好运!

相关问题