【CJsonObject】C++ JSON 解析器使用教程
能选封装的尽量不使用底层的
一、CJsonObject 简介
CJsonObject 是 Bwar 基于 cJSON 全新开发一个 C++ 版的 JSON 库。
CJsonObject 的最大优势是轻量、简单好用,开发效率极高,尤其对多层嵌套 json 的读取和生成、修改极为方便。
CJsonObject比cJSON简单易用得多,且只要不是有意不释放内存就不会发生内存泄漏。
用CJsonObject的好处在于完全不用专门的文档,头文件即文档,看完Demo立刻就会用,所有函数都十分通俗易懂,最为关键的一点是解析JSON和生成JSON的编码效率非常高。
Github 地址:https://github.com/Bwar/CJsonObject
二、CJsonObject 应用
仅需将克隆下来的 Github 仓库中四个文件添加至项目中即可
- cJson.h、cJson.c
- CJsonObject.hpp、 CJsonObject.cpp
// 实际需要导入的头文件
#include "CJsonObject.hpp"
三、Github 自带的Demo
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include "../CJsonObject.hpp"
//int main()
int main(int argc, char* argv[])
{
std::ifstream fin(argv[1]);
if (fin.good())
{
neb::CJsonObject oJson;
std::stringstream ssContent;
ssContent << fin.rdbuf();
if (oJson.Parse(ssContent.str()))
{
std::cout << oJson.ToString() << std::endl;
}
else
{
std::cerr << "parse json error" << "\n";// << ssContent.str() << std::endl;
}
fin.close();
}
int iValue;
double fTimeout;
std::string strValue;
neb::CJsonObject oJson("{\"refresh_interval\":60,"
"\"test_float\":[18.0, 10.0, 5.0],"
"\"test_int\":[135355, -1844674407370955161, -935375],"
"\"timeout\":12.5,"
"\"dynamic_loading\":["
"{"
"\"so_path\":\"plugins/User.so\", \"load\":false, \"version\":1,"
"\"cmd\":["
"{\"cmd\":2001, \"class\":\"neb::CmdUserLogin\"},"
"{\"cmd\":2003, \"class\":\"neb::CmdUserLogout\"}"
"],"
"\"module\":["
"{\"path\":\"im/user/login\", \"class\":\"neb::ModuleLogin\"},"
"{\"path\":\"im/user/logout\", \"class\":\"neb::ModuleLogout\"}"
"]"
"},"
"{"
"\"so_path\":\"plugins/ChatMsg.so\", \"load\":false, \"version\":1,"
"\"cmd\":["
"{\"cmd\":2001, \"class\":\"neb::CmdChat\"}"
"],"
"\"module\":[]"
"}"
"]"
"}");
std::cout << oJson.ToString() << std::endl;
std::cout << "-------------------------------------------------------------------" << std::endl;
std::cout << oJson["dynamic_loading"][0]["cmd"][1]("class") << std::endl;
oJson["dynamic_loading"][0]["cmd"][0].Get("cmd", iValue);
std::cout << "iValue = " << iValue << std::endl;
oJson["dynamic_loading"][0]["cmd"][0].Replace("cmd", -2001);
oJson["dynamic_loading"][0]["cmd"][0].Get("cmd", iValue);
std::cout << "iValue = " << iValue << std::endl;
oJson.Get("timeout", fTimeout);
std::cout << "fTimeout = " << fTimeout << std::endl;
oJson["dynamic_loading"][0]["module"][0].Get("path", strValue);
std::cout << "strValue = " << strValue << std::endl;
std::cout << "-------------------------------------------------------------------" << std::endl;
oJson.AddEmptySubObject("depend");
oJson["depend"].Add("nebula", "https://github.com/RivTian/Nebula");
oJson["depend"].AddEmptySubArray("bootstrap");
oJson["depend"]["bootstrap"].Add("BEACON");
oJson["depend"]["bootstrap"].Add("LOGIC");
oJson["depend"]["bootstrap"].Add("LOGGER");
oJson["depend"]["bootstrap"].Add("INTERFACE");
oJson["depend"]["bootstrap"].Add("ACCESS");
std::cout << oJson.ToString() << std::endl;
std::cout << "-------------------------------------------------------------------" << std::endl;
std::cout << oJson.ToFormattedString() << std::endl;
std::cout << "-------------------------------------------------------------------" << std::endl;
neb::CJsonObject oCopyJson = oJson;
if (oCopyJson == oJson)
{
std::cout << "json equal" << std::endl;
}
oCopyJson["depend"]["bootstrap"].Delete(1);
oCopyJson["depend"].Replace("nebula", "https://github.com/RivTian/CJsonObject");
std::cout << oCopyJson.ToString() << std::endl;
std::cout << "-------------------------key traverse------------------------------" << std::endl;
std::string strTraversing;
while(oJson["dynamic_loading"][0].GetKey(strTraversing))
{
std::cout << "traversing: " << strTraversing << std::endl;
}
std::cout << "---------------add a new key, then key traverse---------------------" << std::endl;
oJson["dynamic_loading"][0].Add("new_key", "new_value");
while(oJson["dynamic_loading"][0].GetKey(strTraversing))
{
std::cout << "traversing: " << strTraversing << std::endl;
}
std::cout << oJson["test_float"].GetArraySize() << std::endl;
float fTestValue = 0.0;
for (int i = 0; i < oJson["test_float"].GetArraySize(); ++i)
{
oJson["test_float"].Get(i, fTestValue);
std::cout << fTestValue << "\t in string: " << oJson["test_float"](i) << std::endl;
}
for (int i = 0; i < oJson["test_int"].GetArraySize(); ++i)
{
std::cout << "in string: " << oJson["test_int"](i) << std::endl;
}
oJson.AddNull("null_value");
std::cout << oJson.IsNull("test_float") << "\t" << oJson.IsNull("null_value") << std::endl;
oJson["test_float"].AddNull();
std::cout << oJson.ToString() << std::endl;
if (oJson.KeyExist("simeout"))
std::cout << "timeout key exist" << std::endl;
neb::CJsonObject oLongLong("{\"long_long\":1283949231388184576}");
int64 llValue = 0;
uint64 ullValue = 0;
oLongLong.Get("long_long", llValue);
oLongLong.Get("long_long", ullValue);
std::cout << "llValue = " << llValue << ", ullValue = " << ullValue << std::endl;
//oJson.Add("json_move", std::move(oLongLong)); // C++11
oJson.AddWithMove("json_move", oLongLong);
std::cout << oJson.ToString() << std::endl;
}
四、用法解析
1、构造方法
CJsonObject(); // 默认的构造方法
CJsonObject(const std::string& strJson); // 通过Json字符串构造
CJsonObject(const CJsonObject* pJsonObject); // 通过对象指针构造
CJsonObject(const CJsonObject& oJsonObject); // 通过拷贝构造函数构造
2、常用方法
CJsonObject& operator=(const CJsonObject& oJsonObject); // 重载赋值操作符
bool operator==(const CJsonObject& oJsonObject) const; // 重载赋值操作符
bool Parse(const std::string& strJson); // 解析json字符串
void Clear(); // 清除内存
bool IsEmpty() const; // 判断解析对象是否为空
bool IsArray() const; // 判断解析对象是否为json数组
std::string ToString() const; // 将解析对象转换为字符串
// ===================== Key ==================================
bool KeyExist(const std::string& strKey) const; // 判断对象是否存在
3、原始 JSON 对象解析主要使用的方法
bool AddEmptySubObject(const std::string& strKey); // 在当前的原始解析对象上添加空的子对象
bool AddEmptySubArray(const std::string& strKey); // 在当前的原始解析对象上添加空的子数组
CJsonObject& operator[](const std::string& strKey); // 重载[]操作符
std::string operator()(const std::string& strKey) const; // 重载()操作符
bool Get(const std::string& strKey, CJsonObject& oJsonObject) const; // 得到与key值相对应的对象键值
bool Get(const std::string& strKey, std::string& strValue) const; // 得到与key值相对应的字符串键值
// 以下的只是根据key值获取不同数据类型的键值
bool Get(const std::string& strKey, int32& iValue) const;
bool Get(const std::string& strKey, uint32& uiValue) const;
bool Get(const std::string& strKey, int64& llValue) const;
bool Get(const std::string& strKey, uint64& ullValue) const;
bool Get(const std::string& strKey, bool& bValue) const;
bool Get(const std::string& strKey, float& fValue) const;
bool Get(const std::string& strKey, double& dValue) const;
// 在相应的key值上添加不同数据类型的键值
bool Add(const std::string& strKey, const CJsonObject& oJsonObject);
bool Add(const std::string& strKey, const std::string& strValue);
bool Add(const std::string& strKey, int32 iValue);
bool Add(const std::string& strKey, uint32 uiValue);
bool Add(const std::string& strKey, int64 llValue);
bool Add(const std::string& strKey, uint64 ullValue);
bool Add(const std::string& strKey, bool bValue, bool bValueAgain);
bool Add(const std::string& strKey, float fValue);
bool Add(const std::string& strKey, double dValue);
// 删除指定的key值
bool Delete(const std::string& strKey);
// 根据key值替代指定的键值
bool Replace(const std::string& strKey, const CJsonObject& oJsonObject);
bool Replace(const std::string& strKey, const std::string& strValue);
bool Replace(const std::string& strKey, int32 iValue);
bool Replace(const std::string& strKey, uint32 uiValue);
bool Replace(const std::string& strKey, int64 llValue);
bool Replace(const std::string& strKey, uint64 ullValue);
bool Replace(const std::string& strKey, bool bValue, bool bValueAgain);
bool Replace(const std::string& strKey, float fValue);
bool Replace(const std::string& strKey, double dValue);
4、JSON 数据使用的主要方法
int GetArraySize(); // 得到json数组的元素数量
CJsonObject& operator[](unsigned int uiWhich); // 重载[]操作符
std::string operator()(unsigned int uiWhich) const; // 重载()操作符
bool Get(int iWhich, CJsonObject& oJsonObject) const; // 得到数组iWhich索引的解析对象
// 根据索引iWhich不同数据类型的数据
bool Get(int iWhich, std::string& strValue) const;
bool Get(int iWhich, int32& iValue) const;
bool Get(int iWhich, uint32& uiValue) const;
bool Get(int iWhich, int64& llValue) const;
bool Get(int iWhich, uint64& ullValue) const;
bool Get(int iWhich, bool& bValue) const;
bool Get(int iWhich, float& fValue) const;
bool Get(int iWhich, double& dValue) const;
// 往数组添加不同数据类型的键值
bool Add(const CJsonObject& oJsonObject);
bool Add(const std::string& strValue);
bool Add(int32 iValue);
bool Add(uint32 uiValue);
bool Add(int64 llValue);
bool Add(uint64 ullValue);
bool Add(int iAnywhere, bool bValue);
bool Add(float fValue);
bool Add(double dValue);
// 往数组添加不同数据类型的键值作为第一个元素
bool AddAsFirst(const CJsonObject& oJsonObject);
bool AddAsFirst(const std::string& strValue);
bool AddAsFirst(int32 iValue);
bool AddAsFirst(uint32 uiValue);
bool AddAsFirst(int64 llValue);
bool AddAsFirst(uint64 ullValue);
bool AddAsFirst(int iAnywhere, bool bValue);
bool AddAsFirst(float fValue);
bool AddAsFirst(double dValue);
// 删除指定索引iWhich的元素
bool Delete(int iWhich);
// 替代指定索引iWhich的元素
bool Replace(int iWhich, const CJsonObject& oJsonObject);
bool Replace(int iWhich, const std::string& strValue);
bool Replace(int iWhich, int32 iValue);
bool Replace(int iWhich, uint32 uiValue);
bool Replace(int iWhich, int64 llValue);
bool Replace(int iWhich, uint64 ullValue);
bool Replace(int iWhich, bool bValue, bool bValueAgain);
bool Replace(int iWhich, float fValue);
bool Replace(int iWhich, double dValue);
#if __cplusplus < 201101L
bool ReplaceAdd(const std::string& strKey, const CJsonObject& oJsonObject);
bool ReplaceAdd(const std::string& strKey, const std::string& strValue);
template <typename T>
bool ReplaceAdd(const std::string& strKey, T value)
{
if (KeyExist(strKey))
{
return(Replace(strKey, value));
}
return(Add(strKey, value));
}
#else
template <typename T>
bool ReplaceAdd(const std::string& strKey, T&& value)
{
if (KeyExist(strKey))
{
return(Replace(strKey, std::forward<T>(value)));
}
return(Add(strKey, std::forward<T>(value)));
}
#endif
五、个人 Demo
1、JSON 参考
{
"requestCode": "200",
"statusCode": 0,
"args":
{
"name": "Koshkaaa",
"age": 22,
"id": 0
}
}
2、JSON 拼接
#include <iostream>
#include "CJsonObject.hpp"
using namespace std;
int main()
{
neb::CJsonObject inputJsonObject;
inputJsonObject.Add("requestCode", "200");
inputJsonObject.Add("statusCode", 0);
neb::CJsonObject argsJsonObject;
argsJsonObject.Add("name", "Koshkaaa");
argsJsonObject.Add("age", 22);
argsJsonObject.Add("id", 0);
inputJsonObject.Add("args", argsJsonObject);
std::cout << "拼凑的Json为:" << inputJsonObject.ToString() << std::endl;
getchar();
return 0;
}
3、JSON 解析
#include <iostream>
#include "CJsonObject.hpp"
using namespace std;
int main()
{
std::string json = "{"
"\"requestCode\": \"200\","
"\"statusCode\": 0,"
"\"args\": "
"{"
"\"name\": \"Koshkaaa\","
"\"age\": 22,"
"\"id\": 0"
"}"
"}";
neb::CJsonObject inputJsonObject(json);
std::string requestCode;
int statusCode;
inputJsonObject.Get("requestCode", requestCode);
inputJsonObject.Get("statusCode", statusCode);
neb::CJsonObject argsJsonObject;
inputJsonObject.Get("args", argsJsonObject);
if (!argsJsonObject.IsEmpty())
{
std::string name;
int age;
int id;
argsJsonObject.Get("name", name);
argsJsonObject.Get("age", age);
argsJsonObject.Get("id", id);
}
getchar();
return 0;
}
参考文章
【CJsonObject】C++ JSON 解析器使用教程的更多相关文章
- 手写Json解析器学习心得
一. 介绍 一周前,老同学阿立给我转了一篇知乎回答,答主说检验一门语言是否掌握的标准是实现一个Json解析器,网易游戏过去的Python入门培训作业之一就是五天时间实现一个Json解析器. 知乎回答- ...
- 一起写一个JSON解析器
[本篇博文会介绍JSON解析的原理与实现,并一步一步写出来一个简单但实用的JSON解析器,项目地址:SimpleJSON.希望通过这篇博文,能让我们以后与JSON打交道时更加得心应手.由于个人水平有限 ...
- 这个东西,写C++插件的可以用到。 RapidJSON —— C++ 快速 JSON 解析器和生成器
点这里 原文: RapidJSON —— C++ 快速 JSON 解析器和生成器 时间 2015-04-05 07:33:33 开源中国新闻原文 http://www.oschina.net/p/ ...
- 如何编写一个JSON解析器
编写一个JSON解析器实际上就是一个函数,它的输入是一个表示JSON的字符串,输出是结构化的对应到语言本身的数据结构. 和XML相比,JSON本身结构非常简单,并且仅有几种数据类型,以Java为例,对 ...
- 自己动手实现一个简单的JSON解析器
1. 背景 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.相对于另一种数据交换格式 XML,JSON 有着诸多优点.比如易读性更好,占用空间更少等.在 ...
- 一个简单的json解析器
实现一个简单地json解析器. 两部分组成,词法分析.语法分析 词法分析 package com.mahuan.json; import java.util.LinkedList; import ja ...
- 高性能JSON解析器及生成器RapidJSON
RapidJSON是腾讯公司开源的一个C++的高性能的JSON解析器及生成器,同时支持SAX/DOM风格的API. 直击现场 RapidJSON是腾讯公司开源的一个C++的高性能的JSON解析器及生成 ...
- spring boot2 修改默认json解析器Jackson为fastjson
0.前言 fastjson是阿里出的,尽管近年fasjson爆出过几次严重漏洞,但是平心而论,fastjson的性能的确很有优势,尤其是大数据量时的性能优势,所以fastjson依然是我们的首选:sp ...
- .Net Core 3.0原生Json解析器
微软官方博客中描述了为什么构造了全新的Json解析器而不是继续使用行业准则Json.Net 微软博客地址:https://devblogs.microsoft.com/dotnet/try-the-n ...
- 高手教您编写简单的JSON解析器
编写JSON解析器是熟悉解析技术的最简单方法之一.格式非常简单.它是递归定义的,所以与解析Brainfuck相比,你会遇到轻微的挑战 ; 你可能已经使用JSON.除了最后一点之外,解析 Scheme的 ...
随机推荐
- swiper轮播图出现疯狂抖动(小程序)
swiper轮播图息屏一段时间或快速滑动切换时出现疯狂抖动 以前做小程序项目的时候,没专门测试人员,都是开发者自测,可能我的手机性能比较不错(哈哈)或时机不对,总之没发掘到这个bug:近期做项目,测试 ...
- Object.assign () 和深拷贝
先看看啥叫深拷贝?啥叫浅拷贝? 假设B复制了A,修改A的时候,看B是否发生变化: 如果B跟着也变了,说明是浅拷贝,拿人手短!(修改堆内存中的同一个值) 如果B没有改变,说明是深拷贝,自食其力!(修改堆 ...
- wps演示编辑常用30个快捷键
下面是关于WPS演示编辑常用的30个快捷键的详细介绍说明: Ctrl + N:新建演示文稿. Ctrl + O:打开演示文稿. Ctrl + S:保存演示文稿. Ctrl + Z:撤销上一步操作. C ...
- 现代统计分析软件Datainside在学生成绩分析中的应用
Datainside(薪火数据)是一款非常常用的统计分析软件,广泛应用于学术研究和商业领域. 在学生成绩分析方面,Datainside提供了丰富的功能和工具,可以帮助教育机构和研究人员深入理解学生的学 ...
- 大数据 - MapReduce:从原理到实战的全面指南
本文深入探讨了MapReduce的各个方面,从基础概念和工作原理到编程模型和实际应用场景,最后专注于性能优化的最佳实践. 关注[TechLeadCloud],分享互联网架构.云服务技术的全维度知识.作 ...
- 一篇文章带你掌握性能测试工具——Jmeter
一篇文章带你掌握性能测试工具--Jmeter 在目前的中大型企业中,仅仅进行功能测试已经不足以满足企业的需求,在重大客户基数下性能测试将会直接影响到用户体验 所以在这篇文章中我们将会学习性能测试的相关 ...
- RIPEMD加密算法:原理、应用与安全性
一.引言 在信息时代,数据安全愈发受到重视,加密算法作为保障信息安全的关键技术,其性能和安全性备受关注.RIPEMD(RACE Integrity Primitives Evaluation Mess ...
- 算法2:Hanoi塔
汉诺(Hanoi)塔 一.背景介绍 在印度,有这么一个古老的传说:在世界中心贝拿勒斯(在印度北部)的圣庙里,一块黄铜板上插着三根宝石针.印度教的主神梵天在创造世界的时候,在其中一根针上从下到上地穿好了 ...
- 【scikit-learn基础】--『监督学习』之 支持向量机回归
在机器学习中,支持向量机(Support Vector Machine)算法既可以用于回归问题,也可以用于分类问题. 支持向量机(SVM)算法的历史可以追溯到1963年,当时前苏联统计学家弗拉基米尔· ...
- 全国网络安全行业职业技能大赛云南省选拔赛 Misc 部分WP
word_sercet 题目 我的解答: 加密文档,010打开图片发现密码 VVV_123.com 解压打开得到flag(注:flag原本是隐藏的,但我之前设置过隐藏文字自动显示,因此这里直接可以看到 ...