通过jsoncpp读取JSON文件
最近需要为C++工程开发一个配置文件功能,经过综合考虑,最后决定使用JSON文件作为配置文件格式。
JSON作为时下最流行的数据交换语言之一,比TXT文件更加简洁明确,比XML更节省存储空间,并且,比数据库更轻巧灵便。在之前的开发经验中,曾经用它来作为配置文件、网络数据传输格式等。JSON由于其简单明晰的数据格式,使得其易于阅读和编辑,也便于机器对其进行解析,因此,最终成为我们的首选。
目前网络上的C++开源JSON库很多,例如RapidJSON、json11、nlohmann、jsoncpp等,想了解更多的同学可参考这位大神的博客:C++中json解析开源库收集,支持json5
我选择的是jsoncpp,不为什么,大概名字更合我心吧哈哈。
1. jsoncpp库安装
方法1,源码安装
jsoncpp的开源代码:GitHub-jsoncpp
大家可以自行下载jsoncpp源码,在自己的系统上编译安装,Linux和Windows均可。
方法2,apt-get安装
在Linux系统上,偷了个懒,直接通过apt-get安装了jsoncpp,命令行如下。
sudo apt-get install libjsoncpp-dev
libjsoncpp.so默认安装路径为/usr/lib/x86_64-linux-gnu/libjsoncpp.so,头文件路径:/usr/include/jsoncpp/json/json.h。如果以上路径不在系统环境变量中,请自行添加。
2. Demo
jsoncpp在解析JSON文件时最重要的两个结构是Json::Reader和Json::Value。其中,Json::Reader的主要功能是将文件流或字符串解析到Json::Value中,主要使用parse函数;Json::Value可以表示所有支持的类型,如:int、double、string、object、array等。
下面我们通过一个小demo来说明其基本的使用方法。
首先,制作一个JSON文件:
{
"name": "Grace",
"sex": "woman",
"age": 28,
"marriage": true,
"education": {
"university": "USTC",
"major": "Automation",
"courses":["Information Technology", "Automatic Control Theory", "Image Processing"]
}
}
下面是读取以上JSON文件的C++代码:
#include <iostream>
#include <fstream>
#include <string>
#include "jsoncpp/json/json.h" //头文件在/usr/include/jsoncpp/json/json.h
using namespace std;
int main(int argc, char **argv)
{
const char *config_file = NULL;
if(argc > 1)
{
config_file = (const char*)argv[1]; // Get input json file
}
else
{
config_file = "config.json"; // If not specified, use the default file name
}
Json::Reader json_reader;
Json::Value json_value;
ifstream infile(config_file, ios::binary);
if(!infile.is_open())
{
cout << "Open config file failed!" << endl;
return -1;
}
if(json_reader.parse(infile, json_value))
{
string name = json_value["name"].asString(); // 读取字符串型参数
string sex = json_value["sex"].asString();
int age = json_value["age"].asInt(); // 读取int型参数
bool marriage = json_value["marriage"].asBool(); // 读取布尔型参数
string university = json_value["education"]["university"].asString(); //读取嵌套类型
string major = json_value["education"]["major"].asString();
Json::Value courses = json_value["education"]["courses"]; // 读取值为Array的类型
cout << "name = " << name << endl;
cout << "sex = " << sex << endl;
cout << "age = " << age << endl;
cout << "marriage = " << marriage << endl;
cout << "Education informatin: " << endl;
cout << " university: " << university << endl;
cout << " major: " << major << endl;
cout << " Courses:";
for(int i = 0; i < courses.size(); i++)
{
cout << courses[i].asString();
if(i != (courses.size() - 1))
{
cout << ", ";
}
else
{
cout << ".";
}
}
cout << endl;
}
else
{
cout << "Can not parse Json file!";
}
infile.close();
return 0;
}
编译:
g++ -std=c++11 test_jsoncpp.cpp -o test_jsoncpp -ljsoncpp
执行: