標籤:style blog color io os ar div sp log
#include <iostream>#include <boost/property_tree/ptree.hpp>#include <boost/property_tree/json_parser.hpp>#include <sstream>#include <string>using namespace std;//stringstream只是一個中轉的作用,因為write_json還是read_json操作的是stringstream.void packetage(char** json)//不能直接用char* json,因為傳遞的指標的值會變,需要傳遞指標的地址{ boost::property_tree::ptree tree; tree.put("a", 1); tree.put("b", 2); std::stringstream ss; //將ptree的內容寫到stringstream中,寫的內容就是Json格式,這裡用stringstream這個是固定模式 boost::property_tree::json_parser::write_json(ss, tree); *json = new char[ss.str().size() + 1];//需要為/0分配一個位置 //*json = const_cast<char*>(ss.str().c_str());//這種方式不行或者const_case也不行,可能是因為stringstream內部實現的原因 strcpy(*json, ss.str().c_str());//只能這種方式將其內部字串拷貝出來}void parse(char* json){ boost::property_tree::ptree tree; std::stringstream ss(json); boost::property_tree::json_parser::read_json<boost::property_tree::ptree>(ss, tree);//將ss中的json讀取到ptree中 int a = tree.get<int>("a"); int b = tree.get<int>("b");}int main(){ //----------------先來個Json解析和封裝------------------- //1.封裝json /*就來個簡單的 { "a":1, "b":2 }*/ char* json = NULL; packetage(&json); parse(json); getchar(); return 0;}
json封裝與解析