c++ 使用nlohmann_json库解析json文件

本文介绍了如何在c++中利用nlohmann_json库解析json文件,包括无结构、单层结构和多层结构的json。详细讲述了安装nlohmann_json库的步骤,并提供了不同结构json文件的解析示例代码及其运行结果。
摘要由CSDN通过智能技术生成

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值