c++ boost Json 生成与解析
- 示例Json字符串,涉及json对象,json对象数组,json数组
{ "type": 2, "area": [ { "id": 0, "name": "test0", "entry": 1, "exit": 2, "point": [ 1, 2, 3, 4 ] } ] }
- Boost json 字符串生成
void genJsonString() { boost::property_tree::ptree root; boost::property_tree::ptree areas_item; root.put("type", 2); std::vector<int> area_list_ = {1}; std::vector<int> station_list_ = {1,2,3,4}; for (auto s : area_list_) { boost::property_tree::ptree item; item.put("id", 1); item.put("name", std::string("test")); item.put("entry", 1); item.put("exit", 2); boost::property_tree::ptree points; for (auto p : station_list_) { boost::property_tree::ptree point; point.put_value(p); points.push_back(std::make_pair("", point)); } item.add_child("point", points); areas_item.push_back(std::make_pair("", item)); } root.add_child("area", areas_item); }
- Boost json 字符串解析
template <class T> bool getJsonValue(boost::property_tree::ptree &pt, T &value, const std::string §) { try { value = pt.get<T>(sect); } catch (boost::property_tree::ptree_bad_path&){ return false; } return true; } void parseJsonString(const std::string &str) { boost::property_tree::ptree pt; std::stringstream sstream(str); boost::property_tree::json_parser::read_json(sstream, pt); int rst = getJsonValue<int>(pt, type, "type"); if (!rst) { return; } if (type != 2) { return; } std::vector<int> area_list_; boost::property_tree::ptree child_pt = pt.get_child("area"); for (auto item : child_pt) { boost::property_tree::ptree area = item.second; int id,entry,exit; getJsonValue<int>(pt, id, "id"); if (!rst) { return; } getJsonValue<int>(pt, entry, "entry"); if (!rst) { return; } getJsonValue<int>(pt, exit, "exit"); if (!rst) { return; } getJsonValue<std::string>(pt, name, "name"); if (!rst) { return; } std::vector<int> station_list; for (auto vitem : area.get_child("point")) { int point = 0; bool error_format = false; try { point = boost::lexical_cast<int>(vitem.second.data()); } catch(boost::bad_lexical_cast & e) { SYSLOG(WARNING) << "not valid number string "; error_format = true; } if (error_format == false) { station_list.push_back(point); } } area_list_.push_back(id); } }
- boost Json生成json对象存在的问题
如果value 是数字的话,boost会给数字加上引号。例如 {"type": "2"},但如果想要 {"type": 2}这种格式,需要额外的处理。
std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); std::string input_str_after_replace = std::regex_replace(input_str, reg, "$1");
该解决版本拷贝自 https://stackoverflow.com/questions/2855741/why-boost-property-tree-write-json-saves-everything-as-string-is-it-possible-to