ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ### boost库解析json ***** #### 待解析待json数据 ``` {"status": "0", "data": {"login_name":"1"} } ``` #### 解析示例 `ptree.get<int>("data") = ptree.get_child("data").get_value<int>()` ``` #include <iostream> #include <string> #include <sstream> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> int test() { std::string s = "{\"status\": \"0\", \"data\": {\"login_name\":\"1\"} }" std::stringstream ss(s); boost::property_tree::ptree ptree; boost::property_tree::read_json(ss, ptree); std::cout << "input text:" << std::endl; boost::property_tree::write_json(std::cout, ptree); std::cout << "-------------------------" << std::endl; std::cout << "data.login_name:" << ptree.get<std::string>("data.login_name") << std::endl; } ``` ### 解析json数组 ***** #### 待解析一维数组 ``` {"status":["1","2"]} ``` #### 示例 ``` #include <iostream> #include <string> #include <sstream> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> int test() { std::string s = "{\"status\": [\"1\",\"2\"]}" std::stringstream ss(s); boost::property_tree::ptree ptree; boost::property_tree::read_json(ss, ptree); std::cout << "input text:" << std::endl; for (auto &item: ptree.get_child("status")) { std::cout <<item.second.get_value<int>()<< std::endl; } } ``` #### 待解析多维数组 ``` "{\n" " \"status\": \"0\",\n" " \"data\": {\n" " \"login_name\": \"12123\",\n" " \"user_name\": \"\",\n" " \"ssid\": \"\",\n" " \"time\": \"\",\n" " \"onlineinfos\": [\n" " {\n" " \"platform\": \"1\",\n" " \"status\": \"0\",\n" " \"status_desc\": \"\",\n" " \"server_name\": \"LoginYet\",\n" " \"client_ver\": \"5.6\",\n" " \"mac\": \"\",\n" " \"ip\": \"192.168.0.1\",\n" " \"login_time\": \"\",\n" " \"is_back_online\": \"\",\n" " \"back_online_flag\": \"\"\n" " }\n" " ]\n" " }\n" "}" ``` #### 示例 ``` std::string s = "{\n" " \"status\": \"0\",\n" " \"data\": {\n" " \"login_name\": \"12123\",\n" " \"user_name\": \"\",\n" " \"ssid\": \"\",\n" " \"time\": \"\",\n" " \"onlineinfos\": [\n" " {\n" " \"platform\": \"1\",\n" " \"status\": \"0\",\n" " \"status_desc\": \"\",\n" " \"server_name\": \"LoginYet\",\n" " \"client_ver\": \"5.6\",\n" " \"mac\": \"\",\n" " \"ip\": \"192.168.0.1\",\n" " \"login_time\": \"\",\n" " \"is_back_online\": \"\",\n" " \"back_online_flag\": \"\"\n" " }\n" " ]\n" " }\n" "}"; std::stringstream ss(s); boost::property_tree::ptree ptree; boost::property_tree::read_json(ss, ptree); std::cout << "input text:" << std::endl; boost::property_tree::write_json(std::cout, ptree); std::cout << "-------------------------" << std::endl; std::cout << "data.login_name:" << ptree.get<std::string>("data.login_name") << std::endl; for (auto &item: ptree.get_child("data.onlineinfos")) { std::cout <<item.second.get<std::string>("platform")<< std::endl; } } ```