rapidjson安装学习

article/2025/10/4 7:57:13

这里主要记录几个要点,后面来补充吧,很晚了
源码是鹅厂大佬写的,佩服佩服~

一、RapidJSON介绍及资料

RapidJSON是腾讯开源的C++ JSON解析及生成器,只有头文件的C++库,跨平台。
RapidJSON 是一个 C++ 的 JSON 解析器及生成器。它的灵感来自 RapidXml。
特点:

  • 小而全。 同时支持SAX和DOM风格API
  • 快。性能可与 strlen() 相比
  • 独立。不依赖BOOST 等外部库。它甚至不依赖于 STL
  • 对内存友好。在大部分 32/64 位机器上,每个 JSON 值只占 16 字节(除字符串外)。它预设使用一个快速的内存分配器,令分析器可以紧凑地分配内存。【和rapidxml内存池思想类似】
  • 对Unicode友好,支持各种编码。

学习资料:
官方GitHub:https://github.com/Tencent/rapidjson
官方文档:http://rapidjson.org/zh-cn/index.html

二、安装

官方手册:https://legacy.gitbook.com/book/miloyip/rapidjson/details/zh-cn

执行 git submodule update --init 去获取 thirdparty submodules (google test)。
在 rapidjson 目渌下,建立一个 build 目录。
在 build 目录下执行 cmake .. 命令以设置生成。Windows 用户可使用 cmake-gui 应用程序。
在 Windows 下,编译生成在 build 目录中的 solution。在 Linux 下,于 build 目录运行 make。

参考rapidjson使用简介和RapidJSON简介及使用
这个可用学习判断成员是否存在、判断类型、最后取值的思想,避免错误使用,引起内核core dump。

三、实现

demo1:

// rapidjson/example/simpledom/simpledom.cpp`
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
using namespace rapidjson;
int main() {
// 1. 把 JSON 解析至 DOM。
const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
Document d;
d.Parse(json);
// 2. 利用 DOM 作出修改。
Value& s = d["stars"];
s.SetInt(s.GetInt() + 1);
// 3. 把 DOM 转换(stringify)成 JSON。
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
// Output {"project":"rapidjson","stars":11}
std::cout << buffer.GetString() << std::endl;
return 0;
}

在这里插入图片描述

demo2:
针对如下的json串:
在这里插入图片描述
dom树实现:
在这里插入图片描述
代码:

// Hello World example
// This example shows basic usage of DOM-style API.#include "rapidjson/document.h"     // rapidjson's DOM-style API
#include "rapidjson/prettywriter.h" // for stringify JSON
#include <cstdio>using namespace rapidjson;
using namespace std;int main(int, char*[]) {// 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.#if 0// "normal" parsing, decode strings to new buffers. Can use other input stream via ParseStream().if (document.Parse(json).HasParseError())return 1;
#else// 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;
#endifprintf("\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;
}

http://chatgpt.dhexx.cn/article/I34mTv6t.shtml

相关文章

rapidjson安装使用

前言&#xff1a;仅个人小记。 正文 由于 rapidjson是 “header-only”的C库&#xff0c;故而直接将头文件目录拷贝到系统目录或者指定目录即可完成安装。 参考材料&#xff1a; rapidjson代码仓库 https://github.com/Tencent/rapidjson rapidjson 文档 https://rapidjson.…

rapidjson创建json字符串

参考链接&#xff1a;http://rapidjson.org/zh-cn/ #include "json/stringbuffer.h" #include "json/prettywriter.h"void getJson() {rapidjson::StringBuffer buf;rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buf);writer.StartObj…

RapidJson踩坑记录

用于记录RapidJson使用中的坑位&#xff0c;持续更新。关于rapidjson的详细说明&#xff0c;可以参加参考文档&#xff1a;http://rapidjson.org/zh-cn/md_doc_tutorial_8zh-cn.html#CreateString 1、添加字符串元素 现象&#xff1a; #include "rapidjson/document.h&…

c++ rapidjson

下面rapid json代码已在vs2017验证&#xff0c;特别地&#xff0c;用rapid json可以解析中文字符串&#xff0c;不会中文乱码。 第一步&#xff1a;去https://github.com/Tencent/rapidjson/上下载头文件&#xff0c;只需要其中的include文件夹。也可以在csdn上下载&#xff1…

RapidJSON简介及使用

RapidJSON是腾讯开源的一个高效的C JSON解析器及生成器&#xff0c;它是只有头文件的C库。RapidJSON是跨平台的&#xff0c;支持Windows, Linux, Mac OS X及iOS, Android。它的源码在GitHub - Tencent/rapidjson: A fast JSON parser/generator for C with both SAX/DOM style …

JSON--rapidjson介绍

JSON--rapidjson 1 RapidJSON简介2 C/C Json库对比一致性解析时间解析内存Stringify Time&#xff08;string 2 json&#xff09;Prettify Time&#xff08;美化格式时间&#xff09;代码大小 3 几个重点库介绍rapidjsonnlohmann-jsonjsoncppcjson 参考 1 RapidJSON简介 Rapid…

RapidJSON入门:手把手教入门实例介绍

RapidJSON优点 跨平台 编译器&#xff1a;Visual Studio、gcc、clang 等 架构&#xff1a;x86、x64、ARM 等 操作系统&#xff1a;Windows、Mac OS X、Linux、iOS、Android 等 容易安装 只有头文件的库。只需把头文件复制至你的项目中。 独立、最小依赖 不需依赖 STL、BOOST …

oracle listagg如何去重

listagg去重 去重思路&#xff1a;利用listagg会忽略null值的特点 按ENTITY_GROUP_RRN 分组&#xff0c;用 listagg 分别合并 EQPT_ID 与 STATION_ID &#xff0c;同时要求去重 表 T_TEST 数据如下&#xff1a; EQPT_IDENTITY_GROUP_RRNSTATION_IDTOOL-00110493721JITAI-1TO…

mysql listagg within_Oracle的 listagg() WITHIN GROUP ()函数使用

1.使用条件查询 查询部门为20的员工列表 -- 查询部门为20的员工列表 SELECT t.DEPTNO,t.ENAME FROM SCOTT.EMP t where t.DEPTNO 20 ; 效果&#xff1a; 2.使用 listagg() WITHIN GROUP () 将多行合并成一行 SELECT T .DEPTNO, listagg (T .ENAME, ,) WITHIN GROUP (ORDER …

listagg结果去重

最近在一个项目中用到了listagg方法&#xff0c;但是在组合结果中出现有重复的情况。默认的结果如下 于是我就写了一个方法对listagg的结果去重&#xff0c;也可以对该格式的字符串去重&#xff0c;方法如下 create or replace function listaggpure(targetStr varchar2,seper…

Oracle函数之listagg函数

语法 有点难以看懂&#xff0c;个人理解listagg是list aggregate的缩写&#xff08;错了勿喷&#xff09;&#xff0c;也就是列表总计&#xff0c;聚合的意思。 官方文档解释为&#xff1a; LISTAGG orders data within each group specified in the ORDER BY clause and then …

listagg()行转列函数

--基础数据 DROP TABLE "ZYH_TEST"; CREATE TABLE "ZYH_TEST" ("ID" NUMBER(19) NOT NULL ,"NAME" VARCHAR2(255 BYTE) ,"CREATETIME" DATE ,"SCORE" NUMBER ,"CLASSID" VARCHAR2(255 BYTE) )INSERT I…

oracle listagg支持,PostgreSQL行列转换(兼容oracle listagg)

oracle11g开始支持的listagg函数替代了wmconcat来实现行列转换的功能。 listagg函数的用法: oracle行列转换例子: —建表https://www.cndba.cn/foucus/article/3929https://www.cndba.cn/foucus/article/3929 SQL> create table b (id number,name varchar2(20)); Table c…

mysql listagg函数_SQLSERVER中的ListAGG

跃然一笑 MySQLSELECT FieldA , GROUP_CONCAT(FieldB ORDER BY FieldB SEPARATOR ,) AS FieldBs FROM TableName GROUP BY FieldA ORDER BY FieldA;Oracle&DB2SELECT FieldA , LISTAGG(FieldB, ,) WITHIN GROUP (ORDER BY FieldB) AS FieldBs FROM TableName GRO…

mysql listagg within_Oracle函数之LISTAGG

最近在学习的过程中&#xff0c;发现一个挺有意思的Oracle函数&#xff0c;它可实现对列值的拼接。下面我们来看看其具体用法。 最近在学习的过程中&#xff0c;发现一个挺有意思的Oracle函数&#xff0c;它可实现对列值的拼接。下面我们来看看其具体用法。 用法&#xff1a; 对…

listagg

1.创建数据表&#xff0c;准备测试数据 CREATE TABLE MK_STUDENT(ID NUMBER(18) NOT NULL,STU_NAME VARCHAR2(200),STU_SCORE VARCHAR2(50),PRIMARY KEY (ID) ); ALTER TABLE MK_STUDENT ADD KEMU VARCHAR2(200);INSERT INTO MK_STUDENT (ID,STU_NAME,STU_SCORE,KEMU) VALUES …

listagg( )详解

想象一个场景&#xff0c;现实生活中一个人有许多手机号已是常态&#xff0c;数据库中也会有类似的结构。 大家肯定想知道listagg()有什么样的效果&#xff1a; 案列分析 一个表中有许多数据&#xff0c;名字叫张三的有许多手机号。希望查询结果出来是分组且清晰。 select …

Oracle列转行函数 Listagg()详解

详解 listagg()函数可以实现多列记录聚合为一条记录&#xff0c;从而实现数据的压缩、致密化&#xff08;data densification&#xff09; 基本用法 像聚合函数一样&#xff0c;通过Group by语句&#xff0c;把每个Group的一个字段&#xff0c;拼接起来 LISTAGG(XXX,XXX) WI…

Oracle 中 LISTAGG 函数的介绍以及使用

LISTAGG 函数介绍 listagg 函数是 Oracle 11.2 推出的新特性。 其主要功能类似于 wmsys.wm_concat 函数&#xff0c; 即将数据分组后&#xff0c; 把指定列的数据再通过指定符号合并。LISTAGG 使用 listagg 函数有两个参数&#xff1a;1、 要合并的列名2、 自定义连接符号☆L…