将 cpprestsdk json 值对象写入文件

Write a cpprestsdk json value object into a file

本文关键字:文件 对象 cpprestsdk json      更新时间:2023-10-16

我收到一个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:%un", 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文件中,但不确定如何完成它。写入ostream对象并打开someValueserialize.c_cstr()会产生奇怪的输出。

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

如果你的系统 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();