如何:使用 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 语句。

以下是使用 web::http::client::http_response::extract_json 方法从 HTTP GET 响应提取 JSON 数据的方法。 有关检索服务器响应但不使用 JSON 的更基础的版本,请参阅如何:连接到 HTTP 服务器

C++
// 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"http://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)
    */
}


以下是使用 web::json::value 类在内存中生成 JSON 值,并循环访问它的值的方法。 web::json::value::cbegin 和web::json::value::cend 方法返回值集合的只读迭代器。

C++
// 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
    */
}


以下是完整示例。

C++
#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"http://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();
}

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值