json封装与解析

#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;
}
原文地址:https://www.cnblogs.com/zzyoucan/p/3971774.html