解析JSON文件布尔值,下面是我跟着从JSON文件读取值的步骤:访问使用升压属性树
{
"Bases":[
{
"mnemonic":"ADIS.LA.01",
"relay":true
},
{
"mnemonic":"ALEX.LA.01",
"relay":true
}
]
}
我无法获取布尔值。
在下面的代码,我:
- 打开JSON文件
- 设置根元素,并开始该根元素下遍历childtree(碱基)
- 撷取的每一标签的值并将它们保存到适当的变量类型。
代码:
ReadJsonFile()
{
using boost::property_tree::ptree;
const boost::property_tree::ptree& propTree
boost::property_tree::read_json(ss, pt);
const std::string rootElement = "Bases";
boost::property_tree::ptree childTree;
bool m_relay;
try
{
/** get_child - Get the child at the given path, or throw @c ptree_bad_path. */
childTree = propTree.get_child(rootElement);
}
catch (boost::property_tree::ptree_bad_path& ex)
{
return false;
}
BOOST_FOREACH(const boost::property_tree::ptree::value_type &v, propTree.get_child(rootElement)){
string vID;
for (ptree::const_iterator subTreeIt = v.second.begin(); subTreeIt != v.second.end(); ++subTreeIt) {
if (subTreeIt->first == "mnemonic")
{
// Get the value string and trim the extra spaces, if any
vID = boost::algorithm::trim_copy(subTreeIt->second.data());
}
if (subTreeIt->first == "relay")
{
m_relay = boost::algorithm::trim_copy(subTreeIt->second.data());
}
}
}
}
错误:
error: cannot convert ‘std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ to ‘bool’ in assignment
显然,布尔值"relay":true
被视为一个字符串而不是bool
。
如果我改变
bool m_relay;
到
std::string m_relay;
代码工作正常,但bool
类型未能进行编译。
我错过了什么吗?
可能想看看在https://stackoverflow.com/questions/4597048/boost-property-tree-iterators-如何处理他们 –
我看了一下,它并没有提供有关使用ptree :: const_iterator获取boolen值的信息,因此我提出了问题 – LearningCpp
@LearningCpp:实际上,它确实提供了如何获取不同数据的细节类型,如果你仔细阅读它。尝试使用'm_relay = subTreeIt->秒。get_value();'而不是'm_relay = boost :: algorithm :: trim_copy(subTreeIt-> second.data());' –