C++ Json 的几个操作

一直用的Jsoncpp这个库,用了很多次,隔几日不用了就又忘记怎么操作了唉,还是老老实实写下来,免得要用又去查资料!

1,读含有数组的json

const char* str = "{\"HELK\": [\"id\",\"name\",\"yantao\",\"gender\",\"Male\"],\"code\": 100,\"msg\": \"\",\"files\": \"\"}";  
Json::Reader reader;  
Json::Value root;  
if (reader.parse(str, root))  // reader将Json字符串解析到root,root将包含Json里所有子元素   
{
    bool IsArray=root["HELK"].isArray();

    for(int i=0;i<root["HELK"].size();++i)
    {
        std::string  value=root["HELK"][i].toStyledString();
        printf("%s\n",value.c_str());
    }
}

JPG:
这里写图片描述


2.读obj里面的obj

const char* str = "{\"uploadid\": {\"id\":\"123454\",\"name\":\"yantao\",\"gender\":\"Male\"},\"code\": 100,\"msg\": \"\",\"files\": \"\"}";  
Json::Reader reader;  
Json::Value root;  
reader.parse(str, root);  // reader将Json字符串解析到root,root将包含Json里所有子元素   
Json::Value obj=root["uploadid"];
string str2 = obj["id"].asString();
printf("%s\n",str2.c_str());

JPG:
这里写图片描述


3.生成一个json

Json::Value root; 
root["id"]=1244235;
root["describe"]="how SB you are";
Json::StyledWriter sw;
std::string res_str = sw.write(root);
std::cout << res_str << std::endl;

这里写图片描述


4.生成一个json里面有数组

Json::Value root; 
root["id"]=1244235;
root["describe"]="how SB you are";
root["Arry"].append("123");
root["Arry"].append("213");
root["Arry"].append("321");
Json::StyledWriter sw;
std::string res_str = sw.write(root);
std::cout << res_str << std::endl;

这里写图片描述


更多文章:http://blog.csdn.net/what951006
powered by:小乌龟在大乌龟背上~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值