如何:使用 JSON 資料 (C++ REST SDK)

您可以使用 C++ REST SDK (Codename "Casablanca") web::json 命名空間,更快剖析 JSON 資料。 本頁顯示兩個範例。 第一個範例示範如何從 HTTP GET 回應擷取 JSON 資料。 第二個範例在記憶體中建立 JSON 值,並逐一查看其值。

警告

本主題包含 C++ REST SDK 1.0 (Codename "Casablanca") 的資訊。如果使用 Codeplex Casablanca 網頁上的較新版本,則請使用 http://casablanca.codeplex.com/documentation 上的本機文件。

在這些範例之後,還有更完整示範 #include 和 using 陳述式的範例。

從 HTTP GET 回應擷取 JSON 資料

以下說明如何使用 web::http::client::http_response::extract_json 方法,從 HTTP GET 回應擷取 JSON 資料。 如需可擷取伺服器回應但不使用 JSON 的更基本版本,請參閱如何:連接至 HTTP 伺服器

// Retrieves a JSON value from an HTTP request.
pplx::task<void> RequestJSONValueAsync()
{
    // TODO: To successfully use this example, you must perform the request 
    // against a server that provides JSON data. 
    // This example fails because the returned Content-Type is text/html and not application/json.
    http_client client(L"https://www.fourthcoffee.com");
    return client.request(methods::GET).then([](http_response response) -> pplx::task<json::value>
    {
        if(response.status_code() == status_codes::OK)
        {
            return response.extract_json();
        }

        // Handle error cases, for now return empty json value...
        return pplx::task_from_result(json::value());
    })
        .then([](pplx::task<json::value> previousTask)
    {
        try
        {
            const json::value& v = previousTask.get();
            // Perform actions here to process the JSON value...
        }
        catch (const http_exception& e)
        {
            // Print error.
            wostringstream ss;
            ss << e.what() << endl;
            wcout << ss.str();
        }
    });

    /* Output:
    Content-Type must be application/json to extract (is: text/html)
    */
}

在記憶體中建立 JSON 值,並逐一查看其值

以下說明如何使用 web::json::value 類別,在記憶體中建立 JSON 值,並對其值執行迴圈。 web::json::value::cbeginweb::json::value::cend 方法會傳回值集合的唯讀迭代器。

// Demonstrates how to iterate over a JSON object.
void IterateJSONValue()
{
    // Create a JSON object.
    json::value obj;
    obj[L"key1"] = json::value::boolean(false);
    obj[L"key2"] = json::value::number(44);
    obj[L"key3"] = json::value::number(43.6);
    obj[L"key4"] = json::value::string(U("str"));

    // Loop over each element in the object.
    for(auto iter = obj.cbegin(); iter != obj.cend(); ++iter)
    {
        // Make sure to get the value as const reference otherwise you will end up copying
        // the whole JSON value recursively which can be expensive if it is a nested object.
        const json::value &str = iter->first;
        const json::value &v = iter->second;

        // Perform actions here to process each string and value in the JSON object...
        std::wcout << L"String: " << str.as_string() << L", Value: " << v.to_string() << endl;
    }

    /* Output:
    String: key1, Value: false
    String: key2, Value: 44
    String: key3, Value: 43.6
    String: key4, Value: str
    */
}

完整範例

以下是完整範例。

#include <http_client.h>
#include <iostream>
#include <json.h>

using namespace web;
using namespace web::http;
using namespace web::http::client;

// Retrieves a JSON value from an HTTP request.
pplx::task<void> RequestJSONValueAsync()
{
    // TODO: To successfully use this example, you must perform the request 
    // against a server that provides JSON data. 
    // This example fails because the returned Content-Type is text/html and not application/json.
    http_client client(L"https://www.fourthcoffee.com");
    return client.request(methods::GET).then([](http_response response) -> pplx::task<json::value>
    {
        if(response.status_code() == status_codes::OK)
        {
            return response.extract_json();
        }

        // Handle error cases, for now return empty json value...
        return pplx::task_from_result(json::value());
    })
        .then([](pplx::task<json::value> previousTask)
    {
        try
        {
            const json::value& v = previousTask.get();
            // Perform actions here to process the JSON value...
        }
        catch (const http_exception& e)
        {
            // Print error.
            wostringstream ss;
            ss << e.what() << endl;
            wcout << ss.str();
        }
    });

    /* Output:
    Content-Type must be application/json to extract (is: text/html)
    */
}

// Demonstrates how to iterate over a JSON object.
void IterateJSONValue()
{
    // Create a JSON object.
    json::value obj;
    obj[L"key1"] = json::value::boolean(false);
    obj[L"key2"] = json::value::number(44);
    obj[L"key3"] = json::value::number(43.6);
    obj[L"key4"] = json::value::string(U("str"));

    // Loop over each element in the object.
    for(auto iter = obj.cbegin(); iter != obj.cend(); ++iter)
    {
        // Make sure to get the value as const reference otherwise you will end up copying
        // the whole JSON value recursively which can be expensive if it is a nested object.
        const json::value &str = iter->first;
        const json::value &v = iter->second;

        // Perform actions here to process each string and value in the JSON object...
        std::wcout << L"String: " << str.as_string() << L", Value: " << v.to_string() << endl;
    }

    /* Output:
    String: key1, Value: false
    String: key2, Value: 44
    String: key3, Value: 43.6
    String: key4, Value: str
    */
}

int wmain()
{
    // This example uses the task::wait method to ensure that async operations complete before the app exits. 
    // In most apps, you typically don�t wait for async operations to complete.

    wcout << L"Calling RequestJSONValueAsync..." << endl;
    RequestJSONValueAsync().wait();

    wcout << L"Calling IterateJSONValue..." << endl;
    IterateJSONValue();
}

請參閱

其他資源

C++ REST SDK (Codename "Casablanca")