json文件以键值对形式记录信息,因提供了第三方接口函数便于文件信息而广泛作为配置文件使用。
一、linux系统下的安装
可通过指令直接安装:
sudo apt-get install libjsoncpp-dev
二、Json文件的解析
1、解析键值对信息并保存所有键值对信息到一个map容器
void ReadJsonFile(const std::string& json_file1) {
Json::Reader reader;
Json::Value root;
std::map<string, string> map_infor;
std::cout << "read: " << json_file1 << endl;
ifstream in_json1(json_file1, ios::binary);
if (!in_json1.is_open()) {
std::cout << "Error opening json file" << endl;
exit(0);
}
std::cout << "start parse json file" << endl;
if (reader.parse(in_json1, root)) {
Json::Value::Members members = root.getMemberNames();
for (auto& json_key_1 : members) {
map_infor.emplace(json_key_1, root[json_key_1].asString());
}
} else {
std::cout << "Parse json file error" << endl;
exit(0); // 解析文件失败退出
}
in_json1.close();
return;
}
2、直接提取数据信息
void ReadJsonFile(const std::string& json_file2) {
Json::Reader reader;
Json::Value root;
string id_1;
string id_2;
std::cout << "Read json file: " << json_file2 << endl;
ifstream in_json2(json_file2, ios::binary);
if (reader.parse(in_json2, root)) {
id_1 = root["id_1"].asString();
id_2 = root["id_2"].asString();
}
else {
std::cout << "Parse json file error" << endl;
exit(0);
}
in_json2.close();
return;
}