当前位置:   article > 正文

c++ 使用nlohmann_json库解析json文件_nlohmann_json-config.cmake

nlohmann_json-config.cmake

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"
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这种简单结构的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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

项目文件目录
在这里插入图片描述

编译

g++ test.cpp -o test  -std=c++11 -I .
  • 1

运行结果
在这里插入图片描述

2、单层结构json

config.json

{
   
	student:{
   
		"name": "lisi",
		"age": 11,
		"phone": "123456789",
		"address": "aaaaaaa"
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

上面的json文件,类似于c++的结构或者类,可以用结构体表示出来,

namespace nc{
   
	struct student
	{
   
		string name;
		int age;
		string phone;
		string address;
	};

	void from_json(const json&
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/460471
推荐阅读
相关标签
  

闽ICP备14008679号