1. 程式人生 > >Jsoncpp未知Json獲取所有Key和Value

Jsoncpp未知Json獲取所有Key和Value

場景:要獲取某個Json資料,但不知道Json資料的key。如:{"item_key1":"item_value1","item_key2":"item_value2","item_key3":"item_value3"}
解決:關鍵是如何獲取到key,有了key,就可以獲取到value了。可用通過getMemberNames函式獲取key,之後通過key獲取value

string strJson = "{"item_key1":"item_value1","item_key2":"item_value2","item_key3":"item_value3"}";
Json::Value valRoot;  
Json::Reader reader; if (!reader.parse(strJson, valRoot)) { return JSON_PARSE_ERR; } Json::Value::Members members; members = valRoot.getMemberNames(); // 獲取所有key的值 for (Json::Value::Members::iterator iterMember = members.begin
(); iterMember != members.end(); iterMember++) // 遍歷每個key { std::string strKey = *iterMember; if (valRoot[strKey.c_str()].isString()) { std::string strVal = valRoot[strKey.c_str()].asString(); std::cout<<strKey.c
_str()<<":"<<strVal.c_str()<<std::endl; } else if (valRoot[strKey.c_str()].isInt()) { int iVal = valRoot[strKey.c_str()].asInt(); std::cout<<strKey.c_str()<<":"<<iVal<<std::endl; } else if (valRoot[strKey.c_str()].isDouble()) { double dVal = valRoot[strKey.c_str()].asDouble(); std::cout<<strKey.c_str()<<":"<<dVal<<std::endl; } else { std::string strVal = valRoot[strKey.c_str()].toStyledString(); std::cout<<strKey.c_str()<<":"<<strVal.c_str()<<std::endl; } }