C++库---json

c++操作json需要单独的库文件,而不像php那样直接$data = array()搞定的。

所以先去下载c++的json库文件,再尊称规定的语法来实现c++下的json增删改等操作。

1、新增一个json

Json::Value root    //新增json数据root,root的类型可以是int, string, obj, array...

2、在json中添加数据

root.append(12345);          //output : [12345]
root["key"].append("this is routine array in key");    //添加常规数组,output : {"key":[this is routine array in key]}

root["key"]="add a relation array"        //添加关联数组,output : {"key":"add a relation array"}

3、json->string(write将json value转换成字符串)

jsoncpp中的Json::Write 是个纯虚类,不能直接使用,只有调用他的子类,Json::FastWrite(普通输出)和Json::StyleWrite(格式化输出)

Json::Value admin;
admin["admin_key"]=555;
Json::FastWriter fast_write;
cout<<fast_write.write(admin)<<endl;
//output : {"admin_key":555}

Json::Value admin;
admin["admin_key"]=555;
Json::StyleWriter style_write;
cout<<style_write.write(admin)<<endl;
//output: 
//{
//   "admin_key" : 555
//}

4、string->json(read将字符串写入json value)

Json::Value root;
std::string abc = "{"key":"this is value"}";
Json::Reader reader;
reader.parse(abc,root);
Json::StyledWriter style_write;

注意:如果json数组中没有某个key,但不小心使用(调用)了该key,系统会自动为期增加一个key:null

Json::Value admin;
admin["admin_key"]=555;
int bbb = admin["key"].asInt();    //输出admin,结果如下:{"admin_key":555,"key":null}

所以在使用key时,必须判断该key是否存在

if (root.isMember("key")){     //判断key存在不
    cout<<"exist"<<endl;
}
else{
    cout<<"no-exist"<<endl;
}
if (!root["key"].isNull())       //判断存在不,不存在会自动创建一个
{
    cout<<"exist"<<endl;
}
else{
    cout<<"no-exist but i'll create one,the value is null"<<endl;
}    
原文地址:https://www.cnblogs.com/alazalazalaz/p/4118986.html