RapidJSON介绍

1.简介

RapidJSON 是一个 C++ 的 JSON 解析库,由腾讯开源。

  • 支持 SAX 和 DOM 风格的 API,并且可以解析、生成和查询 JSON 数据。
  • RapidJSON 快。它的性能可与strlen() 相比。可支持 SSE2/SSE4.2 加速。
  • RapidJSON 独立。它不依赖于 BOOST 等外部库。它甚至不依赖于STL。
  • RapidJSON 对内存友好。在大部分 32/64 位机器上,每个 JSON 值只占 16字节(除字符串外)。它预设使用一个快速的内存分配器,令分析器可以紧凑地分配内存。
  • RapidJSON 对 Unicode 友好。它支持UTF-8、UTF-16、UTF-32 (大端序/小端序),并内部支持这些编码的检测、校验及转码。例如,RapidJSON 可以在分析一个。
  • RapidJSON 是跨平台的。

2.环境搭建

下载地址:https://github.com/Tencent/rapidjson/tree/v1.1.0
这里使用的版本1.1.0
在这里插入图片描述
下载完成之后解压目录如下,将整个include目录拷贝到我们的工程目录下。

在这里插入图片描述
拷贝完成之后如下图所示:
在这里插入图片描述
配置文件路径。C/C++ ->常规 ->附加包含目录
在这里插入图片描述

3.代码示例

DOM接口示例

#include "rapidjson/document.h"     // rapidjson's DOM-style API
#include "rapidjson/prettywriter.h" // for stringify JSON
#include <iostream>

using namespace rapidjson;

int main()
{
	
	// 1. Parse a JSON text string to a document.
	const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } ";
	printf("Original JSON:\n %s\n", json);

	Document document;  // Default template parameter uses UTF8 and MemoryPoolAllocator.

	// In-situ parsing, decode strings directly in the source string. Source must be string.
	char buffer[sizeof(json)];
	memcpy(buffer, json, sizeof(json));
	if (document.ParseInsitu(buffer).HasParseError())
		return 1;

	printf("\nParsing to document succeeded.\n");

	
	// 2. Access values in document. 

	printf("\nAccess values in document:\n");
	assert(document.IsObject());    // Document is a JSON value represents the root of DOM. Root can be either an object or array.

	assert(document.HasMember("hello"));
	assert(document["hello"].IsString());
	printf("hello = %s\n", document["hello"].GetString());

	// Since version 0.2, you can use single lookup to check the existing of member and its value:
	Value::MemberIterator hello = document.FindMember("hello");
	assert(hello != document.MemberEnd());
	assert(hello->value.IsString());
	assert(strcmp("world", hello->value.GetString()) == 0);
	(void)hello;

	assert(document["t"].IsBool());     // JSON true/false are bool. Can also uses more specific function IsTrue().
	printf("t = %s\n", document["t"].GetBool() ? "true" : "false");

	assert(document["f"].IsBool());
	printf("f = %s\n", document["f"].GetBool() ? "true" : "false");

	printf("n = %s\n", document["n"].IsNull() ? "null" : "?");

	assert(document["i"].IsNumber());   // Number is a JSON type, but C++ needs more specific type.
	assert(document["i"].IsInt());      // In this case, IsUint()/IsInt64()/IsUint64() also return true.
	printf("i = %d\n", document["i"].GetInt()); // Alternative (int)document["i"]

	assert(document["pi"].IsNumber());
	assert(document["pi"].IsDouble());
	printf("pi = %g\n", document["pi"].GetDouble());

	{
		const Value& a = document["a"]; // Using a reference for consecutive access is handy and faster.
		assert(a.IsArray());
		for (SizeType i = 0; i < a.Size(); i++) // rapidjson uses SizeType instead of size_t.
			printf("a[%d] = %d\n", i, a[i].GetInt());

		int y = a[0].GetInt();
		(void)y;

		// Iterating array with iterators
		printf("a = ");
		for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)
			printf("%d ", itr->GetInt());
		printf("\n");
	}

	// Iterating object members
	static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" };
	for (Value::ConstMemberIterator itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr)
		printf("Type of member %s is %s\n", itr->name.GetString(), kTypeNames[itr->value.GetType()]);

	
	// 3. Modify values in document.

	// Change i to a bigger number
	{
		uint64_t f20 = 1;   // compute factorial of 20
		for (uint64_t j = 1; j <= 20; j++)
			f20 *= j;
		document["i"] = f20;    // Alternate form: document["i"].SetUint64(f20)
		assert(!document["i"].IsInt()); // No longer can be cast as int or uint.
	}

	// Adding values to array.
	{
		Value& a = document["a"];   // This time we uses non-const reference.
		Document::AllocatorType& allocator = document.GetAllocator();
		for (int i = 5; i <= 10; i++)
			a.PushBack(i, allocator);   // May look a bit strange, allocator is needed for potentially realloc. We normally uses the document's.

		// Fluent API
		a.PushBack("Lua", allocator).PushBack("Mio", allocator);
	}

	// Making string values.

	// This version of SetString() just store the pointer to the string.
	// So it is for literal and string that exists within value's life-cycle.
	{
		document["hello"] = "rapidjson";    // This will invoke strlen()
		// Faster version:
		// document["hello"].SetString("rapidjson", 9);
	}

	// This version of SetString() needs an allocator, which means it will allocate a new buffer and copy the the string into the buffer.
	Value author;
	{
		char buffer2[10];
		int len = sprintf(buffer2, "%s %s", "Milo", "Yip");  // synthetic example of dynamically created string.

		author.SetString(buffer2, static_cast<SizeType>(len), document.GetAllocator());
		// Shorter but slower version:
		// document["hello"].SetString(buffer, document.GetAllocator());

		// Constructor version: 
		// Value author(buffer, len, document.GetAllocator());
		// Value author(buffer, document.GetAllocator());
		memset(buffer2, 0, sizeof(buffer2)); // For demonstration purpose.
	}
	// Variable 'buffer' is unusable now but 'author' has already made a copy.
	document.AddMember("author", author, document.GetAllocator());

	assert(author.IsNull());        // Move semantic for assignment. After this variable is assigned as a member, the variable becomes null.

	
	// 4. Stringify JSON

	printf("\nModified JSON with reformatting:\n");
	StringBuffer sb;
	PrettyWriter<StringBuffer> writer(sb);
	document.Accept(writer);    // Accept() traverses the DOM and generates Handler events.
	puts(sb.GetString());
	return 0;
}

运行结果:
在这里插入图片描述
SAX接口示例:

#include "rapidjson/document.h"     // rapidjson's DOM-style API
#include "rapidjson/prettywriter.h" // for stringify JSON
#include "rapidjson/reader.h"
#include "rapidjson/error/en.h"
#include <iostream>
#include <string>
#include <map>

using namespace std;
using namespace rapidjson;

typedef map<string, string> MessageMap;

#if defined(__GNUC__)
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(effc++)
#endif

#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(switch - enum)
#endif

struct MessageHandler : public BaseReaderHandler<UTF8<>, MessageHandler>
{
	MessageHandler() : messages_(), state_(kExpectObjectStart), name_() {}

	bool StartObject() 
	{
		switch (state_) 
		{
		case kExpectObjectStart:
			state_ = kExpectNameOrObjectEnd;
			return true;
		default:
			return false;
		}
	}

	bool String(const char* str, SizeType length, bool)
	{
		switch (state_) 
		{
		case kExpectNameOrObjectEnd:
			name_ = string(str, length);
			state_ = kExpectValue;
			return true;
		case kExpectValue:
			messages_.insert(MessageMap::value_type(name_, string(str, length)));
			state_ = kExpectNameOrObjectEnd;
			return true;
		default:
			return false;
		}
	}

	bool EndObject(SizeType) { return state_ == kExpectNameOrObjectEnd; }

	bool Default() { return false; } // All other events are invalid.

	MessageMap messages_;
	enum State
	{
		kExpectObjectStart,
		kExpectNameOrObjectEnd,
		kExpectValue
	}state_;
	std::string name_;
};

#if defined(__GNUC__)
RAPIDJSON_DIAG_POP
#endif

#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif

static void ParseMessages(const char* json, MessageMap& messages)
{
	Reader reader;
	MessageHandler handler;
	StringStream ss(json);
	if (reader.Parse(ss, handler))
		messages.swap(handler.messages_);   // Only change it if success.
	else 
	{
		ParseErrorCode e = reader.GetParseErrorCode();
		size_t o = reader.GetErrorOffset();
		cout << "Error: " << GetParseError_En(e) << endl;;
		cout << " at offset " << o << " near '" << string(json).substr(o, 10) << "...'" << endl;
	}
}

int main()
{
	MessageMap messages;

	const char* json1 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\" }";
	cout << json1 << endl;
	ParseMessages(json1, messages);

	for (MessageMap::const_iterator itr = messages.begin(); itr != messages.end(); ++itr)
		cout << itr->first << ": " << itr->second << endl;

	cout << endl << "Parse a JSON with invalid schema." << endl;
	const char* json2 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\", \"foo\" : {} }";
	cout << json2 << endl;
	ParseMessages(json2, messages);

	return 0;
}

在这里插入图片描述

4.更多参考

libVLC 专栏介绍-CSDN博客

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

QCharts -1.概述-CSDN博客

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/599483.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

ubuntu20安装colmap

系统环境 ubuntu20 &#xff0c;cuda11.8 &#xff0c;也安装了anaconda。因为根据colmap的官方文档说的&#xff0c;如果根据apt-get安装的话&#xff0c;默认是非cuda版本的&#xff0c;而我觉得既然都安装了cuda11.8了&#xff0c;自然也要安装cuda版本的colmap。 安装步骤…

力扣hot100:543. 二叉树的直径/108. 将有序数组转换为二叉搜索树

一、543. 二叉树的直径 LeetCode&#xff1a;543. 二叉树的直径 二叉树的直径 二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。 遇到二叉树的问题很容易去直接用求解的目标去定义递归函数。但是仔细考虑&#xff0c;返回树的直径并不能向上传播。因此我们可以拆…

Git同步代码

Git中5个区&#xff0c;和具体操作&#xff1f; 代码提交和同步代码 代码撤销和撤销同步 平时是怎么提交代码的&#xff1f; 第零步: 工作区与仓库保持一致第一步: 文件增删改&#xff0c;变为已修改状态第二步: git add &#xff0c;变为已暂存状态 $ git status $ git a…

HCIP的学习(OSPF总篇)

HCIA的复习 这边可以与我之前写的HCIA博客结合起来一起看&#xff0c;效果更好 HCIA的学习&#xff08;6&#xff09; OSPF状态机 down—关闭-----一旦启动OSPF进程&#xff0c;并发出hello报文&#xff0c;则进入下一个状态init----初始化状态------当收到的hello报文中存在…

临时邮箱API发送邮件的安全性?如何保障?

临时邮箱API发送邮件的步骤有哪些&#xff1f;设置邮箱API方法&#xff1f; 电子邮件作为一种重要的通信方式&#xff0c;而临时邮箱API作为一种新兴的邮件发送技术&#xff0c;其安全性更是成为大家关注的焦点。那么&#xff0c;临时邮箱API发送邮件的安全性究竟如何呢&#…

leetcode-括号生成-101

题目要求 思路 1.左括号的数量等于右括号的数量等于n作为判出条件&#xff0c;将结果存到res中 2.递归有两种&#xff0c;一种是增加左括号&#xff0c;一种是增加右括号&#xff0c;只要左括号的数量不超过n&#xff0c;就走增加左括号的递归&#xff0c;右括号的数量只要小于…

Qt :信号与槽

信号与槽 信号介绍connect 函数使用connect 函数传参问题 定义槽&#xff08;solt&#xff09;函数方法一方法二 定义信号关键字 signals、emit 定义带参数的信号和槽参数个数不一致问题断开信号和槽的连接 disconnect lambda 表达式 信号介绍 Qt 中&#xff0c;信号会涉及三个…

装饰器模式-原理分析以及动手练习

目录 应用场景涉及的角色和类&#xff08;个人理解&#xff09;涉及的角色组件&#xff08;标准&#xff09;基本实现 Demo&#xff08;可以直接 copy 跑一下看效果&#xff09;自己动手实战需求参考答案 相关话题参考文章 应用场景 需要给一个现有类添加附加功能&#xff0c;…

北京车展现场体验商汤DriveAGI自动驾驶大模型展现认知驱动新境界

在2024年北京国际汽车展的舞台上&#xff0c;众多国产车型纷纷亮相&#xff0c;各自展示着独特的魅力。其中&#xff0c;小米SUV7以其精美的外观设计和宽敞的车内空间&#xff0c;吸引了无数目光&#xff0c;成为本届车展上当之无愧的明星。然而&#xff0c;车辆的魅力并不仅限…

数据库系统理论——绪论

文章目录 前言一、数据库四个基本概念1、数据2、数据库3、数据库管理系统&#xff08;DBMS&#xff09;4、数据库系统&#xff08;DBS&#xff09; 二、数据模型1、概念数据模型2、逻辑数据模型3、物理数据模型 三、三级模式1、图片解析2、二级映像 前言 最近很长时间没更新学…

皮秒激光切割机可以切割材料及主要应用行业

皮秒激光切割机可以切割多种材料&#xff0c;主要应用行业包括但不限于&#xff1a; 1. PCB板行业&#xff1a;主要用于PCB激光分板&#xff0c;如FR4、补强钢片、FPC、软硬结合板、玻纤板等材料的紫外激光切割。 2. 薄膜材料切割&#xff1a;皮秒紫外激光切割机可以直接切割薄…

无法添加以供审核,提交以供审核时遇到意外错误。如果问题仍然存在,请联系我们

遇到问题&#xff1a; 无法添加以供审核 要开始审核流程&#xff0c;必须提供以下项目&#xff1a; 提交以供审核时遇到意外错误。如果问题仍然存在&#xff0c;请联系我们。 解决办法&#xff1a; 修改备案号为小写&#xff0c; 例如&#xff1a;京ICP备2023013223号-2A 改…

选择了软件测试,你后悔吗?

记得在求职的时候&#xff0c;面试官经常问我&#xff1a;“为什么要选择软件测试工作?”而我也会经常说一堆自己有的没的优势去应付。 工作这么久了&#xff0c;也不再浮躁&#xff0c;静下心来回忆当初选择软件测试工作的历程&#xff0c;也是对自己职业生涯的一次回顾。 下…

初始Linux(基础命令)

前言&#xff1a; 我们不能总沉浸在编程语言中&#xff0c;虽然代码能力提升了&#xff0c;但是也只是开胃小菜。我们要朝着更高的方向发展。 最近小编一直在刷力扣&#xff0c;以至于博客更新的比较少。今天就带各位开始学习全新的知识——Linux.至于为啥要学&#xff1f; Lin…

[正则表达式]正则表达式语法与运用(Regular Expression, Regex)

0. 在线工具 RegExr: Learn, Build, & Test RegEx 1. 场景列举 vim Linux命令行 sublime 编辑器 java、python等语言中 ... ... 不同场景、不同版本语法可能不一样 2. 以下示例数据与基本语法 &2024 &As20242024# 2024sA#abdcefgha_bdcefghABASDSADAASDASD…

MySQL之聚合函数与应用

1. 前言 上文我们讲到了单行函数.实际上SQL还有一类叫做聚合函数, 它是对一组数组进行汇总的函数, 输入的是一组数据的集合, 输出的是单个值. 2. 聚合函数 用于处理一组数据, 并对一组数据返回一个值. 有如下几种聚合函数 : AVG(), SUM(), MAX(), MIN(), COUNT(). 3. AVG(…

[蓝桥杯]真题讲解:班级活动(贪心)

[蓝桥杯]真题讲解&#xff1a;班级活动&#xff08;贪心&#xff09; 一、视频讲解二、正解代码1、C2、python33、Java 一、视频讲解 [蓝桥杯]真题讲解&#xff1a;班级活动&#xff08;贪心&#xff09; 二、正解代码 1、C #include<bits/stdc.h> using namespace st…

28.leetcode---前K个高频单词(Java版)

题目链接: https://leetcode.cn/problems/top-k-frequent-words/description/ 题解: 代码: 测试:

Offline:IQL

ICLR 2022 Poster Intro 部分离线强化学习的对价值函数采用的是最小化均方bellman误差。而其中误差源自单步的TD误差。TD误差中对target Q的计算需要选取一个max的动作&#xff0c;这就容易导致采取了OOD的数据。因此&#xff0c;IQL取消max,&#xff0c;通过一个期望回归算子…

QT creator qt6.0 使用msvc2019 64bit编译报错

qt creator qt6.0报错&#xff1a; D:\Qt6\6.3.0\msvc2019_64\include\QtCore\qglobal.h:123: error: C1189: #error: "Qt requires a C17 compiler, and a suitable value for __cplusplus. On MSVC, you must pass the /Zc:__cplusplus option to the compiler."…
最新文章