第一步: 首先安装jsoncpp库 我买的腾讯的云服务器,系统是centos7 下边为安装指令 yum install jsoncpp-devel 安装后,我们只需要在程序中包含头文件 #include<jsoncpp/json/json.h> 就可以使用jsoncpp提供的方法去读写json文件 下边是一些常间的例子 比如对于这个test.json文件内容 { “name” : “xiaohua”, “age” : 18, “sex” : “male” } 读取的方法为 test.cpp: #include #include #include<jsoncpp/json/json.h> using namespace std; void test() { Json::Value root;//内容 Json::Reader reader;//方式为读方式 ifstream in(“test.json”,ios::binary); reader.parse(in,root); cout << root[“name”] .asString()<< endl; cout << root[“age”].asInt()<<endl; cout << root[“sex”].asString() <<endl; in.close(); } int main() { test(); retrun 0; } 我这里没有写一些判断文件是否打开的一些代码,你可以加上 然后g++ -std=c++11 -ljsoncpp test.cpp 可以得到: xiaohua 18 male 写入的方法为 #include #include #include<jsoncpp/json/json.h> using namespace std; void test() { Json::Value root;//内容 root[“name”] = “lihua”; root[“age”] = 18; root[“sex”] = “male”; Json::StyledWriter writer;//为格式写 //Json::FastWirter swriter;//为快速写,建议用上面,看着舒服 string res = writer.write(root); ofstream ofs; ofs.open(“test.json”); ofs << str; ofs.close(); } int main() { test(); retrun 0; } 这样就把上面的内容写入了一个名为test.json 的空文件中 类似的,你可以创建读取或者写入很多个人的信息 比如 [ { “name” : “lihua”, “age” : 18, “sex” : “male” } { “name” : “wangfang”, “age” : 19, “sex” : “female” } ] 读取方法为 void test() { Json::Value root;//内容 Json::Reader reader;//方式为读方式 ifstream in(“test.json”,ios::binary); reader.parse(in,root); for(int i=0;i<root.size();i++) { cout << root[i][“name”] .asString()<< endl; cout << root[i][“age”].asInt()<<endl; cout << root[i][“sex”].asString() <<endl; } in.close(); } int main() { test(); retrun 0; } 就可以得到如下内容 lihua, 18, male “wangfang”, 19, female 写方法类似