我正在尝试从卡萨布兰卡的JSON响应中读取。发送的数据如下所示:
{
"devices":[
{"id":"id1",
"type":"type1"},
{"id":"id2",
"type":"type2"}
]
}有人知道怎么做吗?Casablanca教程似乎只关心创建这样的数组,而不是读取它们。
发布于 2015-10-23 02:43:16
让我们假设您的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()函数将抛出异常。
发布于 2016-12-13 22:44:57
以下是我为解析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();
}https://stackoverflow.com/questions/28833939
复制相似问题