json封裝與解析

來源:互聯網
上載者:User

標籤: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封裝與解析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.