c++解析json文件,可以用开源库nlohmann_json
nlohmann_json下载地址
安装说明
centos 7环境下:
(1)下载源码
$ git clone https://gitee.com/yejiqin/nlohmann_json.git
如果没有安装git命令,root权限下,安装git:
#yum install git -y
编译源码要用到cmake,如果没有安装,可以参考以下文章:
cmake安装说明
(2)下载到本地后,进入源码目录,编译
$cd nlohmann_json
$mkdir build && cd build
$cmake …
$make
$sudo make install
下载后也可以不用编译,把nlohmann_json\include\nlohmann\json.hpp文件和nlohmann_json\include\nlohmann文件夹放到项目目录就行。
本文采用不编译的方式
1、解析无结构json文件
config.json
{
"name": "zhangsan",
"age": 20,
"address": "xxxxxxxxx"
}
这种简单结构的json文件,可以直接用 json.at(typename) 读取数据出来。
test.cpp
#include "json.hpp"
#include <iostream>
#include <fstream>
using namespace std;
//为了方便,用json等价于nlohmann::json
using json = nlohmann::json;
int main()
{
ifstream jfile("config.json");
if(!jfile.is_open())
{
cout<<"open json file error..."<<endl;
return -1;
}
cout<<"open json file success..."<<endl;
json nj;
jfile >> nj;
string name = nj.at("name");
int age = nj.at("age");
string address = nj.at("address");
cout<<"name="<<name<<endl;
cout<<"age="<<age<<endl;
cout<<"address="<<address<<endl;
return 0;
}
项目文件目录
编译
g++ test.cpp -o test -std=c++11 -I .
运行结果
2、单层结构json
config.json
{
student:{
"name": "lisi",
"age": 11,
"phone": "123456789",
"address": "aaaaaaa"
}
}
上面的json文件,类似于c++的结构或者类,可以用结构体表示出来,
namespace nc{
struct student
{
string name;
int age;
string phone;
string address;
};
void from_json(const json