如何使用C++ Boost Property Tree读取JSON文件指定节点
使用Boost Property Tree读取JSON中的形状维度数据
你的JSON结构中,所有形状都嵌套在Shapes节点下,原代码存在几个关键错误导致无法运行,以下是修正方案:
原代码的问题
- 节点路径错误:直接访问
root.get_child("Square")找不到对应节点,正确路径应为root.get_child("Shapes.Square") - 变量混淆:循环变量是
result,但代码中错误地访问了名为Square的vector,而非当前遍历的节点 - 未定义变量:代码中使用了
results但未声明,实际你定义的vector名为Square - 逻辑错位:vector的命名不合理,应该用来存储维度键值对,而非用形状名命名
修正后的完整代码
#include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <iostream> #include <string> #include <vector> #include <stdexcept> namespace pt = boost::property_tree; // 根据形状名称获取维度数据 std::vector<std::pair<std::string, int>> getShapeDimensions(const pt::ptree& root, const std::string& shapeName) { std::vector<std::pair<std::string, int>> dimensions; try { // 获取指定形状的节点 const pt::ptree& shapeNode = root.get_child("Shapes." + shapeName); // 遍历维度节点 for (const auto& dimension : shapeNode) { // 获取维度名称和整数值 std::string dimName = dimension.first; int dimValue = dimension.second.get_value<int>(); dimensions.emplace_back(dimName, dimValue); } } catch (const pt::ptree_bad_path& e) { std::cerr << "错误:找不到形状 " << shapeName << " - " << e.what() << std::endl; } catch (const pt::ptree_bad_data& e) { std::cerr << "错误:维度数据格式错误 - " << e.what() << std::endl; } return dimensions; } int main() { pt::ptree root; try { // 读取JSON文件 pt::read_json("Example.json", root); } catch (const std::exception& e) { std::cerr << "读取JSON文件失败:" << e.what() << std::endl; return 1; } // 测试读取Square的维度 std::string targetShape = "Square"; auto dimensions = getShapeDimensions(root, targetShape); std::cout << targetShape << " 的维度数据:" << std::endl; for (const auto& dim : dimensions) { std::cout << dim.first << ": " << dim.second << std::endl; } // 可以替换为Rectangle或Triangle测试 // targetShape = "Rectangle"; // dimensions = getShapeDimensions(root, targetShape); // ... return 0; }
代码说明
- 节点路径:通过
"Shapes." + shapeName拼接正确的节点路径,确保能定位到目标形状 - 类型安全:使用
get_value<int>()直接将维度值转为整数,避免字符串转义问题 - 异常处理:捕获路径不存在、数据格式错误等异常,增强代码健壮性
- 复用性:封装成函数
getShapeDimensions,只需传入形状名称即可获取对应维度,符合你的需求
编译时需要链接Boost库,例如使用g++的命令:
g++ your_code.cpp -o shape_reader -lboost_system -lboost_property_tree
内容的提问来源于stack exchange,提问作者Solveit031
相关产品推荐
相关产品推荐

