我想從卡薩布蘭卡的JSON響應中讀取數據。發送的數據如下所示:使用卡薩布蘭卡解析JSON數組
{
"devices":[
{"id":"id1",
"type":"type1"},
{"id":"id2",
"type":"type2"}
]
}
有誰知道該怎麼做?卡薩布蘭卡教程似乎只關心創建這樣的數組,而不是關於從他們讀取。
我想從卡薩布蘭卡的JSON響應中讀取數據。發送的數據如下所示:使用卡薩布蘭卡解析JSON數組
{
"devices":[
{"id":"id1",
"type":"type1"},
{"id":"id2",
"type":"type2"}
]
}
有誰知道該怎麼做?卡薩布蘭卡教程似乎只關心創建這樣的數組,而不是關於從他們讀取。
讓我們假設你有你的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();
注意,沒有錯誤檢查都是在這裏完成,讓我們假定一切正常(--IF沒有,看卡薩布蘭卡文檔和示例) 。
然後可以通過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()
函數將拋出異常。
以下是我在解析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();
}
只是爲了將來的參考記住用戶可能會被帶回這篇文章,這將導致對此答案的其他問題。最好添加必要的所有信息以避免這種情況。 – 2016-12-13 15:21:55
非常感謝您的好回答! – barneytron 2015-11-20 02:36:56
很好,工作! – 2016-06-23 13:10:58
你的回答是正確的。 – Prince 2018-03-06 12:12:00