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

相关文章

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Java使用jar命令配置服务器端口的完整指南

《Java使用jar命令配置服务器端口的完整指南》本文将详细介绍如何使用java-jar命令启动应用,并重点讲解如何配置服务器端口,同时提供一个实用的Web工具来简化这一过程,希望对大家有所帮助... 目录1. Java Jar文件简介1.1 什么是Jar文件1.2 创建可执行Jar文件2. 使用java

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1