我正在玩boost::property_tree::ptree,即使用以下json 文件:
{
"menu":
{
"foo": "true",
"bar": "true",
"value": "102.3E+06",
"popup":
[
{
"value": "New",
"onclick": "CreateNewDoc()"
},
{
"value": "Open",
"onclick": "OpenDoc()"
}
]
}
}
到目前为止,我一直在尝试访问嵌套的“价值”,但没有运气,这就是我所做的:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
int main(int argc, char *argv[])
{
const char *filename = argv[1];
using boost::property_tree::ptree;
ptree pt;
read_json(filename, pt);
std::string v0 = pt.get<std::string>("menu.value"); // ok
//std::string v1 = pt.get<std::string>("menu.popup.value"); // not ok
//std::string v2 = pt.get<std::string>("menu.popup.1.value"); // not ok
//std::string v3 = pt.get<std::string>("menu.popup.''.value"); // not ok
// ugly solution:
BOOST_FOREACH(ptree::value_type &v,
pt.get_child("menu.popup"))
{
const ptree &pt2 = v.second;
std::string s = pt2.get<std::string>("value");
}
return 0;
}
到目前为止,我所有“不好”的尝试都失败了。似乎 string_path 不允许访问整个 ptree,正如人们可以想象的那样(想想 XML 世界中的 XPath)。还是我错过了什么?