1.包含lib_json.lib及头文件
2.code
bool readJson()
{
FILE *fp;
int size = 0;
//二进制方式打开文件
fp = fopen("test.json", "rb");
if (NULL == fp)
{
printf("Error:Open input.c file fail!\n");
return false;
}
//求得文件的大小
fseek(fp, 0, SEEK_END);
size = ftell(fp);
rewind(fp);
char ar[20480];
memset(ar, 0, 20480);
//读文件
fread(ar, 1, size, fp);//每次读一个,共读size次
fclose(fp);
Json::CharReaderBuilder b;
Json::CharReader* reader(b.newCharReader());
JSONCPP_STRING errs;
Json::Value value;
std::string out;
if (reader->parse((char*)ar, (char*)std::strlen((char*)ar), &value, &errs))
{
//解析json对象数组
const Json::Value Obj1 = value["employees"];
int inum1 = Obj1.size();
for (int j = 0; j < inum1; j++)
{
cout << Obj1[j]["firstName"].asString() << endl;
cout << Obj1[j]["lastName"].asString() << endl;
}
//解析json对象
const Json::Value Obj2 = value["c++"];
cout << Obj2["hello"].asString() << endl;
}
else
{
delete reader;
return false;
}
delete reader;
return true;
}
3.json文件
{
"employees": [
{
"firstName": "Bill",
"lastName": "Gates"
},
{
"firstName": "George",
"lastName": "Bush"
},
{
"firstName": "Thomas",
"lastName": "Carter"
}
],
"c++":{
"hello":"world"
}
}