使用RapidJson开源库解析和生成Json数据

2024-05-12 13:12

本文主要是介绍使用RapidJson开源库解析和生成Json数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

RapidJSON介绍

  • RapidJSON是一个高效、轻量级的 C++ JSON 解析器及生成器库,由腾讯公司开源。
  • RapidJSON 是只有头文件的 C++ 库。只需把 include/rapidjson 目录复制到项目中即可使用。
  • 中文文档

使用介绍

基础json数据生成

  • 代码
    •   #include <iostream>#include "rapidjson/document.h"    // 快速JSON文档操作#include "rapidjson/writer.h"      // JSON写入器#include "rapidjson/stringbuffer.h" // 字符串缓冲区,用于存放生成的JSON字符串int main(){// 创建一个新的 JSON 对象rapidjson::Document doc;doc.SetObject();/** rapidjson::StringRef("John") 对源字符串进行了引用,不进行字符串的拷贝* rapidjson::Value("John")     对源字符串进行了拷贝*/// 添加成员// doc.AddMember("name", rapidjson::StringRef("John"), doc.GetAllocator()); doc.AddMember("name", rapidjson::Value("John").Move(), doc.GetAllocator());doc.AddMember("age", rapidjson::Value(30).Move(), doc.GetAllocator());doc.AddMember("score", rapidjson::Value(90.5).Move(), doc.GetAllocator());// 创建字符串缓冲区和写入器rapidjson::StringBuffer buffer;rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);// 将文档写入缓冲区doc.Accept(writer);// 输出生成的 JSON 字符串std::cout << buffer.GetString() << std::endl;return 0;}
      
  • 生成结果(为了查看方便,对结果手动进行了换行)
    •   {"name":"John","age":30,"score":90.5}
      

多级json数据生成

  • 代码

    •   #include <iostream>#include "rapidjson/document.h"    // 快速JSON文档操作#include "rapidjson/writer.h"      // JSON写入器#include "rapidjson/stringbuffer.h" // 字符串缓冲区,用于存放生成的JSON字符串int main(){// 创建 RapidJson 文档对象和内存分配器rapidjson::Document doc;doc.SetObject();rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();doc.AddMember("code", rapidjson::Value(10010).Move(), allocator);// 第一层数据doc.AddMember("person", rapidjson::Value().SetObject(), allocator);doc["person"].AddMember("name", rapidjson::Value("John").Move(), allocator);doc["person"].AddMember("age", rapidjson::Value(30).Move(), allocator);doc["person"].AddMember("score", rapidjson::Value(90.5).Move(), allocator);doc.AddMember("class", rapidjson::Value("5").Move(), allocator);// 序列化 JSON 到字符串rapidjson::StringBuffer buffer;rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);doc.Accept(writer);// 输出生成的 JSON 字符串std::cout << buffer.GetString() << std::endl;return 0;}
      
  • 生成结果

    •   {"code":10010,"person":{"name":"John","age":30,"score":90.5},"class":"5"}
      

含有数组的json数据生成

  • 代码
    •   #include <iostream>#include "rapidjson/document.h"    // 快速JSON文档操作#include "rapidjson/writer.h"      // JSON写入器#include "rapidjson/stringbuffer.h" // 字符串缓冲区,用于存放生成的JSON字符串int main(){// 创建 RapidJson 文档对象和内存分配器rapidjson::Document doc;doc.SetObject();rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();doc.AddMember("code", rapidjson::Value(10010).Move(), allocator);// 第一层数据doc.AddMember("person", rapidjson::Value().SetObject(), allocator);doc["person"].AddMember("name", rapidjson::Value("John").Move(), allocator);doc["person"].AddMember("age", rapidjson::Value(30).Move(), allocator);doc["person"].AddMember("score", rapidjson::Value(90.5).Move(), allocator);doc.AddMember("class", rapidjson::Value("5").Move(), allocator);rapidjson::Value interests(rapidjson::kArrayType);interests.PushBack(rapidjson::Value("math").Move(), allocator);interests.PushBack(rapidjson::Value("chinese").Move(), allocator);interests.PushBack(rapidjson::Value("english").Move(), allocator);doc.AddMember("lesson", interests, allocator);// 序列化 JSON 到字符串rapidjson::StringBuffer buffer;rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);doc.Accept(writer);// 输出生成的 JSON 字符串std::cout << buffer.GetString() << std::endl;return 0;}
      
  • 生成结果
    •   {"code":10010,"person":{"name":"John","age":30,"score":90.5},"class":"5","lesson":["math","chinese","english"]}
      

含有数组对象的json数据生成

  • 代码
    •   #include <iostream>#include "rapidjson/document.h"    // 快速JSON文档操作#include "rapidjson/writer.h"      // JSON写入器#include "rapidjson/stringbuffer.h" // 字符串缓冲区,用于存放生成的JSON字符串int main(){// 创建 RapidJson 文档对象和内存分配器rapidjson::Document doc;doc.SetObject();rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();doc.AddMember("code", rapidjson::Value(10010).Move(), allocator);doc.AddMember("person", rapidjson::Value().SetObject(), allocator);doc["person"].AddMember("name", rapidjson::Value("John").Move(), allocator);doc["person"].AddMember("age", rapidjson::Value(30).Move(), allocator);doc["person"].AddMember("score", rapidjson::Value(90.5).Move(), allocator);doc.AddMember("class", rapidjson::Value("5").Move(), allocator);rapidjson::Value array(rapidjson::kArrayType);array.SetArray();rapidjson::Value obj1(rapidjson::kObjectType);obj1.AddMember("lessonName", rapidjson::StringRef("math"), allocator);obj1.AddMember("time", rapidjson::Value(8).Move(), allocator);array.PushBack(obj1.Move(), allocator);rapidjson::Value obj2(rapidjson::kObjectType);obj2.AddMember("lessonName", rapidjson::StringRef("chinese"), allocator);obj2.AddMember("time", rapidjson::Value(9).Move(), allocator);array.PushBack(obj2.Move(), allocator);rapidjson::Value obj3(rapidjson::kObjectType);obj3.AddMember("lessonName", rapidjson::StringRef("english"), allocator);obj3.AddMember("time", rapidjson::Value(6).Move(), allocator);array.PushBack(obj3.Move(), allocator);doc.AddMember("lesson", array, allocator);// 序列化 JSON 到字符串rapidjson::StringBuffer buffer;rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);doc.Accept(writer);// 输出生成的 JSON 字符串std::cout << buffer.GetString() << std::endl;return 0;}
      
  • 生成结果
    •   {"code":10010,"person":{"name":"John","age":30,"score":90.5},"class":"5","lesson":[{"lessonName":"math","time":8},{"lessonName":"chinese","time":9},{"lessonName":"english","time":6}]}
      

基础json数据解析

  • json数据
    •   {"name": "John", "age": 30, "score": 19.5}
      
  • 代码
    •   #include <iostream>#include "rapidjson/document.h"    // 快速JSON文档操作#include "rapidjson/writer.h"      // JSON写入器#include "rapidjson/stringbuffer.h" // 字符串缓冲区,用于存放生成的JSON字符串int main(){const char* jsonStr = "{\"name\": \"John\", \"age\": 30, \"score\": 19.5}";// 1. 创建一个 RapidJSON 的 Document 对象来持有 JSON 数据rapidjson::Document d;// 2. 使用 Parse 函数解析 JSON 字符串// 参数ParseFlag::kParseComments 是可选的,用于允许解析带注释的 JSONd.Parse(jsonStr);// 3. 检查解析是否成功if (d.HasParseError()) {std::cerr << "JSON parse error: " << d.GetParseError() << std::endl;return -1;}// 4. 访问 JSON 数据if (d.HasMember("name") && d["name"].IsString()) {std::cout << "Name: " << d["name"].GetString() << std::endl;}if (d.HasMember("age") && d["age"].IsInt()) {std::cout << "age: " << d["age"].GetInt() << std::endl;}if (d.HasMember("score") && d["score"].IsFloat()) {std::cout << "score: " << d["score"].GetFloat() << std::endl;}return 0;}
      
  • 打印
    •   Name: Johnage: 30score: 19.5
      

多级json数据解析

  • json数据
    •   {"code": 10010, "person": {"name": "John", "age": 30,"score": 90.5 },"class": "5"}
      
  • 代码
    •   #include <iostream>#include "rapidjson/document.h"    // 快速JSON文档操作#include "rapidjson/writer.h"      // JSON写入器#include "rapidjson/stringbuffer.h" // 字符串缓冲区,用于存放生成的JSON字符串int main(){const char* jsonStr = "{\"code\": 10010, \"person\": {\"name\": \"John\", \"age\": 30,\"score\": 90.5 },\"class\": \"5\"}";// 1. 创建一个 RapidJSON 的 Document 对象来持有 JSON 数据rapidjson::Document d;// 2. 使用 Parse 函数解析 JSON 字符串// 参数ParseFlag::kParseComments 是可选的,用于允许解析带注释的 JSONd.Parse(jsonStr);// 3. 检查解析是否成功if (d.HasParseError()) {std::cerr << "JSON parse error: " << d.GetParseError() << std::endl;return -1;}if (d.HasMember("code") && d["code"].IsInt()) {std::cout << "code: " << d["code"].GetInt() << std::endl;}if (d.HasMember("person")) {if (d["person"].HasMember("name") && d["person"]["name"].IsString()) {std::cout << "person->name: " << d["person"]["name"].GetString() << std::endl;}if (d["person"].HasMember("age") && d["person"]["age"].IsInt()) {std::cout << "person->age: " << d["person"]["age"].GetInt() << std::endl;}if (d["person"].HasMember("score") && d["person"]["score"].IsFloat()) {std::cout << "person->score: " << d["person"]["score"].GetFloat() << std::endl;}}if (d.HasMember("class") && d["class"].IsString()) {std::cout << "class: " << d["class"].GetString() << std::endl;}return 0;}
      
  • 打印
    •   code: 10010person->name: Johnperson->age: 30person->score: 90.5class: 5
      

含有数组的json数据解析

  • json数据
    •   {"code": 10010, "lesson": ["math", "chinese", "english"], "class": "5"}
      
  • 代码
    •   #include <iostream>#include "rapidjson/document.h"    // 快速JSON文档操作#include "rapidjson/writer.h"      // JSON写入器#include "rapidjson/stringbuffer.h" // 字符串缓冲区,用于存放生成的JSON字符串int main(){const char* jsonStr = "{\"code\": 10010, \"lesson\": [\"math\", \"chinese\", \"english\"], \"class\": \"5\"}";// 1. 创建一个 RapidJSON 的 Document 对象来持有 JSON 数据rapidjson::Document d;// 2. 使用 Parse 函数解析 JSON 字符串// 参数ParseFlag::kParseComments 是可选的,用于允许解析带注释的 JSONd.Parse(jsonStr);// 3. 检查解析是否成功if (d.HasParseError()) {std::cerr << "JSON parse error: " << d.GetParseError() << std::endl;return -1;}if (d.HasMember("code") && d["code"].IsInt()) {std::cout << "code: " << d["code"].GetInt() << std::endl;}if (d.HasMember("lesson") && d["lesson"].IsArray()) {const rapidjson::Value& lesson = d["lesson"];std::cout << "lesson";for (rapidjson::SizeType i = 0; i < lesson.Size(); i++) {if (lesson[i].IsString()) {std::cout << "\t" << lesson[i].GetString() << std::endl;}}}if (d.HasMember("class") && d["class"].IsString()) {std::cout << "class: " << d["class"].GetString() << std::endl;}return 0;}
      
  • 打印
    •   code: 10010lesson  mathchineseenglishclass: 5
      

含有数组对象的json数据解析

  • json数据
    •   {"code": 10010, "lesson":[{"lessonName": "math", "time": 8},{"lessonName": "chinese", "time": 9},{"lessonName": "english", "time":6}]}
      
  • 代码
    •   #include <iostream>#include "rapidjson/document.h"    // 快速JSON文档操作#include "rapidjson/writer.h"      // JSON写入器#include "rapidjson/stringbuffer.h" // 字符串缓冲区,用于存放生成的JSON字符串int main(){const char* jsonStr = "{\"code\": 10010, \"lesson\":[{\"lessonName\": \"math\", \"time\": 8},{\"lessonName\": \"chinese\", \"time\": 9},{\"lessonName\": \"english\", \"time\":6}]}";// 1. 创建一个 RapidJSON 的 Document 对象来持有 JSON 数据rapidjson::Document d;// 2. 使用 Parse 函数解析 JSON 字符串// 参数ParseFlag::kParseComments 是可选的,用于允许解析带注释的 JSONd.Parse(jsonStr);// 3. 检查解析是否成功if (d.HasParseError()) {std::cerr << "JSON parse error: " << d.GetParseError() << std::endl;return -1;}if (d.HasMember("code") && d["code"].IsInt()) {std::cout << "code: " << d["code"].GetInt() << std::endl;}if (d.HasMember("lesson") && d["lesson"].IsArray()) {const rapidjson::Value& employeesArray = d["lesson"];for (rapidjson::SizeType i = 0; i < employeesArray.Size(); i++) {if (employeesArray[i].IsObject()) {const rapidjson::Value& employee = employeesArray[i];std::cout << "lesson " << i << ":" << std::endl;if (employee.HasMember("lessonName") && employee["lessonName"].IsString()) {std::cout << "\t" << "lessonName: " << employee["lessonName"].GetString() << std::endl;}if (employee.HasMember("time") && employee["time"].IsInt()) {std::cout << "\t" << "time: " << employee["time"].GetInt() << std::endl;}}}}return 0;}
      
  • 打印
    •   code: 10010lesson 0:lessonName: mathtime: 8lesson 1:lessonName: chinesetime: 9lesson 2:lessonName: englishtime: 6
      

修改、移除、新增json节点

  • json数据
    •   {"code": 10010, "person": {"name": "John", "age": 30,"score": 90.5 },"class": "5"}
      
  • 代码
    •   #include <iostream>#include "rapidjson/document.h"    // 快速JSON文档操作#include "rapidjson/writer.h"      // JSON写入器#include "rapidjson/stringbuffer.h" // 字符串缓冲区,用于存放生成的JSON字符串int main(){// 1. 把 JSON 解析至 DOM。const char* json = "{\"code\": 10010, \"person\": {\"name\": \"John\", \"age\": 30,\"score\": 90.5 },\"class\": \"5\"}";rapidjson::Document d;d.Parse(json);// 2. 利用 DOM 作出修改。rapidjson::Value& code = d["code"];code.SetInt(10020);rapidjson::Value& name = d["person"]["name"];name.SetString("Jack");// 移除某个节点d.RemoveMember("class");// 新增节点rapidjson::Value newValue("6", d.GetAllocator());d.AddMember("classTemp", newValue, d.GetAllocator());// 3. 把 DOM 转换(stringify)成 JSON。rapidjson::StringBuffer buffer;rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);d.Accept(writer);std::cout << buffer.GetString() << std::endl;return 0;}
      
  • 打印
    •   {"code":10020,"person":{"name":"Jack","age":30,"score":90.5},"classTemp":"6"}
      

这篇关于使用RapidJson开源库解析和生成Json数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/982728

相关文章

MyBatis-Plus通用中等、大量数据分批查询和处理方法

《MyBatis-Plus通用中等、大量数据分批查询和处理方法》文章介绍MyBatis-Plus分页查询处理,通过函数式接口与Lambda表达式实现通用逻辑,方法抽象但功能强大,建议扩展分批处理及流式... 目录函数式接口获取分页数据接口数据处理接口通用逻辑工具类使用方法简单查询自定义查询方法总结函数式接口

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析(结合应用场景)

《nginx-t、nginx-sstop和nginx-sreload命令的详细解析(结合应用场景)》本文解析Nginx的-t、-sstop、-sreload命令,分别用于配置语法检... 以下是关于 nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析,结合实际应

MyBatis中$与#的区别解析

《MyBatis中$与#的区别解析》文章浏览阅读314次,点赞4次,收藏6次。MyBatis使用#{}作为参数占位符时,会创建预处理语句(PreparedStatement),并将参数值作为预处理语句... 目录一、介绍二、sql注入风险实例一、介绍#(井号):MyBATis使用#{}作为参数占位符时,会

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr