使用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 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

Java Spring 中 @PostConstruct 注解使用原理及常见场景

《JavaSpring中@PostConstruct注解使用原理及常见场景》在JavaSpring中,@PostConstruct注解是一个非常实用的功能,它允许开发者在Spring容器完全初... 目录一、@PostConstruct 注解概述二、@PostConstruct 注解的基本使用2.1 基本代

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

springboot使用Scheduling实现动态增删启停定时任务教程

《springboot使用Scheduling实现动态增删启停定时任务教程》:本文主要介绍springboot使用Scheduling实现动态增删启停定时任务教程,具有很好的参考价值,希望对大家有... 目录1、配置定时任务需要的线程池2、创建ScheduledFuture的包装类3、注册定时任务,增加、删

使用Python实现矢量路径的压缩、解压与可视化

《使用Python实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1