JSON++介绍

发布于:2024-05-08 ⋅ 阅读:(32) ⋅ 点赞:(0)

1.简介

JSON++ 是一个轻量级的 JSON 解析库,它是 JSON(JavaScript Object Notation)的一个超集。整个代码由一个单独的头文件json.hpp组成,没有库,没有子项目,没有依赖项,没有复杂的构建系统,支持STL语法。

JSON++ 的主要特点如下:

  • 轻量级:JSON++ 的代码量非常小,容易集成到项目中。
  • 易于使用:JSON++ 提供了简洁的 API,可以快速地解析和生成 JSON 数据。
  • 高效:JSON++ 的解析和生成速度非常快。
  • 可移植性:JSON++ 可以在多种编程语言和平台上使用,例如 C、C++、Python、Java 等。

2.环境搭建

下载地址:https://github.com/nlohmann/json/tree/v3.11.0?tab=readme-ov-file
我使用的3.11.0的版本。
在这里插入图片描述
下载完成之后解压目录如下,将整个include目录拷贝到我们的工程目录下。
在这里插入图片描述
拷贝完成之后如下图所示:
在这里插入图片描述
配置文件路径。C/C++ ->常规 ->附加包含目录
在这里插入图片描述

3.代码示例

写入文件

#include <iostream>
#include <nlohmann/json.hpp>
#include <fstream>

using Json = nlohmann::json;
using namespace std;

int main()
{
	// 创建一个 JSON 对象
	Json root;

	// 添加一些数据
	root["name"] = "John Doe";
	root["age"] = 30;
	root["is_student"] = false;

	// 创建一个 JSON 数组
	Json courses;
	courses.push_back("Math");
	courses.push_back("Physics");
	courses.push_back("Chemistry");

	root["courses"] = courses;

	// 输出 JSON 字符串
	std::cout << std::setw(4) << root << '\n';

	//保存到文件中
	// write prettified JSON to another file
	std::ofstream o("pretty.json");
	o << std::setw(4) << root << std::endl;

	return 0;
}

运行截图:
在这里插入图片描述
在这里插入图片描述
读取文件,就以刚才保存的文件为例读取。

#include <iostream>
#include <nlohmann/json.hpp>
#include <fstream>
#include <vector>

using Json = nlohmann::json;
using namespace std;

struct Student
{
	std::string name;
	int age;
	bool is_student;
	std::vector<std::string> courses;
};

int main()
{
	// read a JSON file
	std::ifstream f("pretty.json");
	Json j = Json::parse(f);

	Student stu;

	// iterate the array
	for (Json::iterator it = j.begin(); it != j.end(); ++it)
	{
		std::cout << it.key() << " : " << it.value() << "\n";
		if (it.key() == "name")
		{
			stu.name = it.value();
		}
		else if (it.key() == "age")
		{
			stu.age = it.value();
		}
		else if (it.key() == "is_student")
		{
			stu.is_student = it.value();
		}
		else if (it.key() == "courses")
		{
			stu.courses = it.value();
		}
	}

	return 0;
}

运行截图:
在这里插入图片描述

4.更多参考

libVLC 专栏介绍-CSDN博客

Qt+FFmpeg+opengl从零制作视频播放器-1.项目介绍_qt opengl视频播放器-CSDN博客

QCharts -1.概述-CSDN博客