【问题标题】:C++ REST SDK (Casablanca) web::json iterationC++ REST SDK (Casablanca) web::json 迭代
【发布时间】:2015-07-28 11:10:23
【问题描述】:

https://msdn.microsoft.com/library/jj950082.aspx 有以下代码。

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++ REST SDK 2.6.0,json::value 中似乎没有 cbegin 方法。没有它,什么是遍历key:values的json节点(值)的正确方法?

【问题讨论】:

    标签: c++ json rest casablanca


    【解决方案1】:

    看起来您列出的文档与 1.0 版挂钩:

    本主题包含有关 C++ REST SDK 1.0(代号“Casablanca”)的信息。如果您使用 Codeplex Casablanca 网页中的更高版本,请使用位于 http://casablanca.codeplex.com/documentation 的本地文档。

    查看 2.0.0 版的更新日志,您会发现:

    重大更改 - 更改了对 json 数组和对象执行迭代的方式。不再返回 std::pair<:value json::value> 的迭代器。相反,在 json::array 和 json::object 类上分别有一个用于数组和对象的单独迭代器。这使我们能够进行性能改进并继续进行相应的调整。数组迭代器返回 json::values,对象迭代器现在返回 std::pair

    我检查了 2.6.0 的源代码,你是对的,值类根本没有迭代器方法。看起来您需要做的是从 value 类中获取内部 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"));
    
    // Note the "as_object()" method calls
    for(auto iter = obj.as_object().cbegin(); iter != obj.as_object().cend(); ++iter)
    {
        // This change lets you get the string straight up from "first"
        const utility::string_t &str = iter->first;
        const json::value &v = iter->second;
        ...
    }
    

    最新的文档和版本可以在 GitHub 链接中找到:https://github.com/microsoft/cpprestsdk

    【讨论】:

      猜你喜欢
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多