代码如下
#include <fstream> #include <cassert> #include <string> #include <iostream> #include "json/json.h" #pragma comment(lib,"lib_json.lib") using namespace std; int main() { { //读操作[{"name" : "xiaoy","age" :17},{"name" : "xiaot","age" : 20}] ifstream ifs; ifs.open("f:\\test.json"); assert(ifs.is_open()); Json::Reader reader; Json::Value root; if (!reader.parse(ifs,root,false)) { return -1; } string name; int age; int size = root.size(); for (int i = 0; i < size; i++) { name = root[i]["name"].asString(); age = root[i]["age"].asInt(); cout << name << " " << age << endl; } } { //写操作[{"age":100,"name":"hello world"}] Json::Value root; Json::FastWriter writer; Json::Value person; person["name"] = "hello,world"; person["age"] = 100; root.append(person); string json_file = writer.write(root); ofstream ofs; ofs.open("f:\\test.json"); assert(ofs.is_open()); ofs << json_file; } { //读操作{"name" : "小楼一夜听春雨","age" : 27} ifstream ifs; ifs.open("f:\\test.json"); assert(ifs.is_open()); Json::Reader reader; Json::Value root; if (!reader.parse(ifs,false)) { return -1; } string name = root["name"].asString(); int age = root["age"].asInt(); cout << name << " " << age << endl; } return 0; }原文链接:https://www.f2er.com/json/289732.html