场景:要获取某个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;
}
}