使用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

相关文章

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本