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

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud