使用casablanca解析JSON数组

时间:2015-03-03 14:11:03

标签: c++ json casablanca

我正在尝试阅读卡萨布兰卡的JSON回复。发送的数据如下所示:

{
"devices":[
  {"id":"id1",
   "type":"type1"},
  {"id":"id2",
   "type":"type2"}
]
}

有谁知道怎么做?卡萨布兰卡教程似乎只关心创建这样的数组而不是从它们中读取数据。

2 个答案:

答案 0 :(得分:10)

我们假设您将json作为http响应:

web::json::value json;
web::http::http_request request;

//fill the request properly, then send it:

client
.request(request)
.then([&json](web::http::http_response response)
{
    json = response.extract_json().get();
})
.wait();

请注意,这里没有进行错误检查,所以让我们假设一切正常(如果没有,请参阅Casablanca文档和示例)。

然后可以通过at(utility::string_t)函数读取返回的json。在你的情况下,它是一个数组(你要么知道,要么通过is_array()检查):

auto array = json.at(U("devices")).as_array();
for(int i=0; i<array.size(); ++i)
{
     auto id = array[i].at(U("id")).as_string();
     auto type = array[i].at(U("type")).as_string();
}

通过这个,您可以获得存储在字符串变量中的json响应的条目。

实际上,您可能还想检查响应是否具有相应的字段,例如通过has_field(U("id")),如果是,请通过null检查条目是否不是is_null() - 否则,as_string()函数会抛出异常。

答案 1 :(得分:6)

以下是我在cpprestsdk中解析JSON值时所做的递归函数,如果您想要其他信息或详细说明,请随时询问。

std::string DisplayJSONValue(web::json::value v)
{
    std::stringstream ss;
    try
    {
        if (!v.is_null())
        {
            if(v.is_object())
            {
                // Loop over each element in the object
                for (auto iter = v.as_object().cbegin(); iter != v.as_object().cend(); ++iter)
                {
                    // It is necessary to make sure that you get the value as const reference
                    // in order to avoid copying the whole JSON value recursively (too expensive for nested objects)
                    const utility::string_t &str = iter->first;
                    const web::json::value &value = iter->second;

                    if (value.is_object() || value.is_array())
                    {
                        ss << "Parent: " << str << std::endl;

                        ss << DisplayJSONValue(value);

                        ss << "End of Parent: " << str << std::endl;
                    }
                    else
                    {
                        ss << "str: " << str << ", Value: " << value.serialize() << std::endl;
                    }
                }
            }
            else if(v.is_array())
            {
                // Loop over each element in the array
                for (size_t index = 0; index < v.as_array().size(); ++index)
                {
                    const web::json::value &value = v.as_array().at(index);

                    ss << "Array: " << index << std::endl;
                    ss << DisplayJSONValue(value);
                }
            }
            else
            {
                ss << "Value: " << v.serialize() << std::endl;
            }
        }
    }
    catch (const std::exception& e)
    {
        std::cout << e.what() << std::endl;
        ss << "Value: " << v.serialize() << std::endl;
    }

    return ss.str();
}