前面讲了C/C++生成Json文件,那么JSON文件怎么用C/C++解析呢?
相反的步骤罢了 先把JSON文件加载到内存,在从内存中解析
要解析的文件:
{
"roomNumber": "B06",
"peopleCount": 6,
"roomFreeTabels": 0,
"roomElemName": ["libero", "rock", "martin", "sky", "bingo", "janny"]
}
代码demo
#include <iostream>
#include <fstream>
#include <string>
#include <Windows.h>
#include "cJSON.h"
static int Debug = 1;
using namespace std;
int32_t main(int32_t argc, const char* argv[])
{
char buf[1024];
ifstream fin;
fin.open("cjosn.json", ios_base::in | ios_base::binary);
if (!fin.is_open()) {
cerr << "file open error!" << endl;
return -1;
}
int index = 0;
while (!fin.eof()) {
fin >> buf[index++];
}
buf[index] = '\0';
if (Debug) cout << buf << endl;
string line(50, '-');
cout << line << endl;
fin.close();
cJSON* root = cJSON_Parse(buf);
cJSON* single = NULL;
single = cJSON_GetObjectItem(root, "roomNumber");
printf("roomNumber:%s\n",cJSON_Print(single));
single = cJSON_GetObjectItem(root, "peopleCount");
printf("peopleCount:%s\n", cJSON_Print(single));
single = cJSON_GetObjectItem(root, "roomFreeTabels");
printf("roomFreeTabels:%s\n", cJSON_Print(single));
single = cJSON_GetObjectItem(root, "roomElemName");
printf("roomElemName:");
int len = cJSON_GetArraySize(single);
for (int i = 0; i < len; ++i) {
printf("%s", cJSON_Print(cJSON_GetArrayItem(single, i)));
}
cout << endl;
cJSON_Delete(root);
::system("pause");
return 0;
}
解析的效果:
更多的关于C/C++学习我会在下面的文章中陆续的分享,也可以关注‘奇牛学院’
来一起讨论