user1173240
user1173240

Reputation: 1475

Write a cpprestsdk json value object into a file

I receive a JSON response body as part of a REST request. I would like to write the body of the JSON into a file. A quick way to do this would be to use the web::http::response object itself..

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();
    });

However, after receiving the response body, I extract the JSON from it to calculate some values, after which, as documented, the json cannot be extracted or used again from the response body, so i have to use the web::json::value object.

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

I'd like to write this json::value object, someValue, to a JSON file, but not sure how to get it done. Writing to an ostream object with serialize.c_cstr() on someValue gives weird output.

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

Upvotes: 1

Views: 1344

Answers (1)

Ryan Tucker
Ryan Tucker

Reputation: 11

If your system typdef std::string as a wide string, then outputting via ostream would lead to weird output.

web::json::value::serialize() returns a utility::string_t

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

utility::string_t is typedef as a std::string

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

So something like this would work:

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();

Upvotes: 1

Related Questions