{ "Version": 1, "Metrics": [{ "wingarea": 1341.01, "unit": "FT2" }, { "wingspan": 1350.81, "unit": "Inch" }], "Propulsion": { "Location": { "XEDIC": 22.618, "unit": "FT" } } }
#include <cstdio> #include <iostream> #include <sstream> #include <vector> #include <string> #include <set> #include <exception> #include <iostream> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/foreach.hpp> #include <boost/typeof/typeof.hpp> using namespace std; using namespace boost; namespace pt = boost::property_tree; int main() { pt::ptree tree; string m_file = "./ss.json"; try { // 创建ptree对象 boost::property_tree::ptree json_root; // 读取file文件,并将根节点存储赋值给json_root boost::property_tree::read_json<boost::property_tree::ptree>(m_file, json_root); //1解析键值对 cout << json_root.get<int>("Version") <<endl; //2获取子节点的方法 boost::property_tree::ptree Metrics = json_root.get_child("Metrics"); boost::property_tree::ptree::iterator json_iterator = Metrics.begin(); cout << json_iterator->second.get<double>("wingarea") << endl; cout << json_iterator->second.get<string>("unit") << endl; json_iterator++; cout << json_iterator->second.get<double>("wingspan") << endl; cout << json_iterator->second.get<string>("unit") << endl; //3逐级解析 boost::property_tree::ptree Propulsion = json_root.get_child("Propulsion"); boost::property_tree::ptree Location = Propulsion.get_child("Location"); cout << Location.get<double>("XEDIC") << endl; cout << Location.get<string>("unit") << endl; } catch (std::exception &e) { cout << "Error: " << e.what() << endl; } }