以下是我从 JSON 文件中获取值的步骤:
{
"Bases":[
{
"mnemonic":"ADIS.LA.01",
"relay":true
},
{
"mnemonic":"ALEX.LA.01",
"relay":true
}
]
}
我无法获取布尔值。
在下面的代码中,我是:
- 打开 JSON 文件
- 设置根元素并开始遍历该根元素下的子树(Bases)
- 获取每个标签的值并将它们保存到适当的变量类型。
代码:
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());
}
}
}
}
错误:
错误:无法在赋值中将 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >' 转换为 'bool'
显然,布尔值"relay":true
被视为字符串而不是bool
.
如果我改变
bool m_relay;
至
std::string m_relay;
代码工作正常,但bool
类型无法编译。
我错过了什么吗?