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 iteratorsprintf("a = ");for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)printf("%d ", itr->GetInt());printf("\n");}// Iterating object membersstatic 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 20for (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 APIa.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 JSONprintf("\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)
#endifstruct 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
#endifstatic 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://xiahunao.cn/news/3016246.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

硬件设计 之 RS485通信协议简单介绍及RS485测试波形

1.RS485定义&#xff1a; 增强型低功耗半双工RS-485(Enhanced Low Power Half-Duplesx RS-485 Transceivers) RS-485是一种串行通信标准&#xff0c;也被称为EIA-485或TIA-485。它定义了在多个设备之间进行数据传输的电气特性、信号线路和通信协议。 2.RS485通信电平&#xf…

华为机考入门python3--(23)牛客23- 删除字符串中出现次数最少的字符

分类&#xff1a;字符串 知识点&#xff1a; 访问字典中keychar的值&#xff0c;不存在则返回0 my_dict.get(char, 0) 字典的所有值 my_dict.value() 列表中的最小值 min(my_list) 题目来自【牛客】 import sysdef delete_min_freq_char(s):# 计算字母出现的频次…

贪心算法应用例题

最优装载问题 #include <stdio.h> #include <algorithm>//排序int main() {int data[] { 8,20,5,80,3,420,14,330,70 };//物体重量int max 500;//船容最大总重量int count sizeof(data) / sizeof(data[0]);//物体数量std::sort(data, data count);//排序,排完数…

JSON++介绍

1.简介 JSON 是一个轻量级的 JSON 解析库&#xff0c;它是 JSON&#xff08;JavaScript Object Notation&#xff09;的一个超集。整个代码由一个单独的头文件json.hpp组成&#xff0c;没有库&#xff0c;没有子项目&#xff0c;没有依赖项&#xff0c;没有复杂的构建系统&…

FL Studio20.9水果安装及切换修改中文语言教程

前言 喜欢音乐制作的小伙伴千万不要错过这个功能强大&#xff0c;安装便捷的音乐软件哦&#xff01;如果你们已经下载好了这款软件的话&#xff0c;小编今天在这里就为大家详细讲解下如何安装FL Studio软件&#xff0c;一起来学习吧&#xff01; 注意&#xff1a; &#xff0…

Java_方法引用

方法引用就是把已经有的方法拿过来用&#xff0c;当作函数式接口中抽象方法的方法体。 条件&#xff1a; 1.引用处需要是函数式接口 2.被引用的方法需要已经存在 3.被引用的方法的形参和返回值需要跟抽象方法的形参和返回值保持一致 4.被引用方法的功能需要满足当前的要求 简…

《Fundamentals of Power Electronics》——示例:Buck-Boost转换器模型变为正则形式

为了说明正则电路模型推导的步骤&#xff0c;让我们将buck-boost转换器的等效电路操作成规范形式。buck-boost转换器的一个小信号交流等效电路如下图所示。 为了将上图所示网络转换成正则形式&#xff0c;需要将所有独立源d(t)转换到左侧&#xff0c;而将所有电感转换到右侧与变…

爬虫学习(3)豆瓣电影

代码 import requests import jsonif __name__ "__main__":url https://movie.douban.com/j/chart/top_list#post请求参数处理&#xff08;同get请求一致&#xff09;headers {"User-Agent": Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/53…

HCIP的学习(OSPF总篇)

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

Web实操(6),基础知识学习(24~)

1.[ZJCTF 2019]NiZhuanSiWei1 &#xff08;1&#xff09;进入环境后看到一篇php代码&#xff0c;开始我简单的以为是一题常规的php伪协议&#xff0c;多次试错后发现它并没有那么简单&#xff0c;它包含了基础的文件包含&#xff0c;伪协议还有反序列化 &#xff08;2&#x…

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."…

如何迁移Windows PC数据到统信UOS 1070

原文链接&#xff1a;如何迁移Windows PC数据到统信UOS 1070 Hello&#xff0c;大家好啊&#xff01;随着统信UOS 1070的推出&#xff0c;越来越多的用户和企业选择迁移到这个基于Linux的操作系统&#xff0c;以享受其安全性和稳定性的优势。今天&#xff0c;我们将探讨如何使用…

栈与队列(包括例题一道)

栈 栈的概念 栈&#xff1a;一种特殊的线性表&#xff0c;其只允许在固定的一端进行插入和删除元素操作。 进行数据插入和删除操作的一端 称为栈顶&#xff0c;另一端称为栈底。 栈中的数据元素遵守后进先出 LIFO &#xff08; Last In First Out &#xff09;的原则。 压栈&…

5月7号作业

将一张bmp图片&#xff0c;修改成德国国旗 #include <stdio.h>#include <string.h>#include <unistd.h>#include <stdlib.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <pthread.h>#include <…

【日志记录】---编译器内存对齐优化导致结构体指针引用成员出现地址错位

一&#xff1a;问题现象 在一个跨线程数据处理消息的时候出现了以下内存错位现象&#xff0c;在结构体指针引用的时候出现了成员数据异常 1.【数据源】线程A消息里面赋值的数据 //字节流 message.data[0] (unsigned char)model_brake_disable_type_read(); message.data[1]…

DirClass

DirClass 通过分析&#xff0c;发现当接收到DirClass远控指令后&#xff0c;样本将返回指定目录的目录信息&#xff0c;返回数据中的远控指令为0x2。 相关代码截图如下&#xff1a; DelDir 通过分析&#xff0c;发现当接收到DelDir远控指令后&#xff0c;样本将删除指定目录…

加密杂谈:Base 向上,BSC 向下

Aerdrome 价格走过一轮&#xff0c;Base 一己之力扶持起巅峰 1B Mcap, 2B FDV 的百倍币&#xff0c;秀出了肌肉&#xff0c;其所带来的正外部性也进一步盘活了 Base 生态 反观 BSC 本轮哪怕靴子落地依然没个响&#xff0c;差距在哪里&#xff1f;本 Thread 将以此为切入点探讨…

Material Studio 计算分子静电力、电荷密度以及差分电荷密度

1.先打开Material Studio导入要计算的分子cif文件或者mol文件&#xff0c;直接Flie-Import 2.高斯几何优化一下结构&#xff0c;参数按照我的设置就行&#xff0c;一般通用&#xff0c;后面出问题再调整 3.点完Run后会跳出很多计算过程&#xff0c;不用管&#xff0c;等他计算完…

【UE】利用物理学放置模型(以堆积石块为例)

目录 效果 步骤 一、准备工作 二、设置石块碰撞 三、绘制石块 效果 步骤 一、准备工作 1. 在虚幻商城中安装“Physical Layout Tool”插件 2. 在虚幻编辑器中勾选插件“Physical Layout”插件 3. 在Quixel Bridge中将我们所需要的石块资产添加到项目中 这里我们导入…

typescript 对象数组和函数

typescript 对象数组和函数 对象 在JavaScript中&#xff0c;对象属于非原始类型。对象也是一种符合数组类型&#xff0c;由若干个对象属性构成。对象属性可以是任意数据类型&#xff0c;比如数组&#xff0c;函数或者对象等。当对象属性为函数的时候&#xff0c;称为方法。 …