我正在尝试从 Casablanca 中读取 JSON 响应。发送的数据如下所示:
{
"devices":[
{"id":"id1",
"type":"type1"},
{"id":"id2",
"type":"type2"}
]
}
有人知道怎么做吗? Casablanca 教程似乎只关心创建这样的数组,而不关心从中读取数据。
最佳答案
假设您将 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"))
,如果是,则通过 is_null()
检查条目是否为 null
-- 否则, as_string()
函数抛出异常。
关于c++ - 使用 casablanca 解析 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28833939/