【问题标题】:Write a cpprestsdk json value object into a file将 cpprestsdk json 值对象写入文件
【发布时间】:2020-05-16 08:19:07
【问题描述】:

我收到 JSON 响应正文作为 REST 请求的一部分。我想将JSON 的正文写入文件。一个快速的方法是使用 web::http::response 对象本身..

pplx::task<void> requestTask = fstream::open_ostream(U("testResults.json")).then([=](ostream outFile)
    {
        *fileStream = outFile;
//some work
    })
.then([=](http_response response)
    {
        printf("Received response status code:%u\n", response.status_code());

        // Write response body into the file.
        return response.body().read_to_end(fileStream->streambuf());
    })
    .then([=](size_t s)
    {
        return fileStream->close();
    });

但是,在收到响应正文后,我从中提取 JSON 以计算一些值,之后,如文档所述,无法从 response 正文中提取或再次使用 json,所以我有使用web::json::value 对象。

http::json::value someValue = response.extract_json().get();

我想将此json::value 对象someValue 写入JSON 文件,但不知道如何完成。在someValue 上使用serialize.c_cstr() 写入ostream 对象会产生奇怪的输出。

ostream o("someFile.json"); 
o << setw(4) << someValue.serialize().c_str() << std<<endl;

【问题讨论】:

    标签: c++ json rest cpprest-sdk


    【解决方案1】:

    如果你的系统 typdef std::string 作为一个宽字符串,那么通过 ostream 输出会导致奇怪的输出。

    web::json::value::serialize() 返回一个utility::string_t

    https://microsoft.github.io/cpprestsdk/classweb_1_1json_1_1value.html#a5bbd4bca7b13cd912ffe76af825b0c6c

    utility::string_t 是 typedef 作为std::string

    https://microsoft.github.io/cpprestsdk/namespaceutility.html#typedef-members

    所以这样的事情会起作用:

    std::filesystem::path filePath(L"c:\\someFile.json"); // Assuming wide chars here. Could be U instead of L depending on your setup
    std::wofstream outputFile(filePath);
    outputFile << someJSONValue.serialize().c_str();
    outputFile.close();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      • 2017-06-29
      • 1970-01-01
      • 2018-07-14
      • 2021-05-20
      • 1970-01-01
      相关资源
      最近更新 更多