原文链接:https://blog.csdn.net/IT8343/article/details/112850502
简单地说,可以用isMember()
进行判断存在与否,类型需要使用is....()
具体判断:
#include "../common.h"
#include <jsoncpp/json/json.h>
int main()
{
ifstream readFile("123.json",ios::binary);
if(!readFile.is_open())
{
printf("open fail\n");
return -1;
}
else
{
Json::Reader reader;
Json::Value root;
if(reader.parse(readFile,root)) //reader将文件中的内容解析到root
{
cout << "ID: " << root["ID"].asInt() << endl;
cout << "longitude: " << root["longitude"].asFloat() << endl;
cout << "latitude: " << root["latitude"].asFloat() << endl;
cout << "openFlag: " << root["openFlag"].asBool() << endl;
cout << "name: " << root["name"].asString() << endl;
for(int i = 0; i < root["data"].size(); ++i)
{
printf("data[%d]: %d\n",i,root["data"][i].asInt());
}
/*不加判断会打印值*/
cout << "testSave1:" << root["testSave1"].asString() << endl;
cout << "testSave2:" << root["testSave2"].asFloat() << endl;
cout << "testSave3:" << root["testSave3"].asInt() << endl;
cout << "testSave4:" << root["testSave4"].asBool() << endl;
cout << "testSave5:" << root["testSave5"].asUInt() << endl;
if(root.isMember("testSave6")) //不存在
{
cout << "testSave6:" << root["testSave6"].asUInt() << endl;
}
else
{
cout << "testSave6 is not exist ..." << endl;
}
if(root.isMember("name")) //存在
{
cout << "name:" << root["name"].asString() << endl;
}
else
{
cout << "name is not exist ..." << endl;
}
if(root["test"].isMember("test1")) //二级key类似用法
{
cout << "name:" << root["test"]["test1"].asInt() << endl;
}
else
{
cout << "test.test1 is not exist ..." << endl;
}
if(root["test"].isString()) //类型判断
{
cout << "[test] is string" << endl;
}
if(root["test"].isObject()) //类型判断
{
cout << "[test] is object" << endl;
}
if(root["name"].isString()) //类型判断
{
cout << "[name] is string" << endl;
}
}
else
{
cout << "no reader" << endl;
}
readFile.close();
return 0;
}
}
123.json:
{
"ID": 20,
"longitude": 112.12345,
"latitude": 28.67890,
"num": 123,
"openFlag": true,
"name": "xi xi",
"data": [4, 2, 3, 4, 5],
"test": {
"test1": 1,
"test2": 2
}
}