当前位置: 首页 > news >正文

C++ Json解析库CJsonObject的详细使用(跨平台无须编译成库)

作者:虚坏叔叔
博客:https://xuhss.com

早餐店不会开到晚上,想吃的人早就来了!😄

C++ Json解析库CJsonObject的详细使用(跨平台无须编译成库)

CJsonObject是基于cJSON全新开发一个C++版的JSON库,CJsonObject的最大优势是轻量(只有4个文件,拷贝到自己代码里即可,无须编译成库,且跨平台和编译器)、简单好用,开发效率极高,对多层嵌套json的读取和生成使用非常简单(大部分json解析库如果要访问多层嵌套json的最里层非常麻烦)。

我一直使用的json库是一个较老版本的cJSONcJSON的好处是简单易用,而且只有两个文件,直接复制到自己的代码中就可以用。cJSON也有一个非常容易让初用者头痛的地方,一不小心就造成内存泄漏了。为此,我基于cJSON封装了一个C++版的 CJsonObject,该库比cJSON更简单易用,且只要不是有意不释放内存就不会发生内存泄漏。

CJsonObject的好处在于完全不用文档,看完Demo马上就会用,不明白的看一下头文件就知道,所有函数都十分通俗易懂,最为关键的一点是解析JSON和生成JSON的编码效率非常高。当然,毕竟是经过cJSON封装而来,效率会略低于cJSONcJSON不支持的CJsonObject也不支持。个人认为,既然已经选了json,那一点点的解析性能差异就不重要了,如果追求性能可以选protobuf

感谢IT界的贡献者:

2018年5月 作者:Bwar 把它开源 https://github.com/Bwar/CJsonObject,并将持续维护。

使用说明:

一、第一步添加以下文件到工程目录:

CJsonObject.hppCJsonObject.cppcJSON.hcJSON.c四个文件加入代码目录,与用户自己的代码一起编译即可。

C++ Json解析CJsonObject的详细使用_C++ Json解析之cJsObject

第二步那就很简单了废话不多说来看代码(将Bwar的示例代码复制到int main()中)

官方事例代码:

#include #include #include "../CJsonObject.hpp"int main()
{int iValue;std::string strValue;neb::CJsonObject oJson("{\"refresh_interval\":60,""\"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]["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/Bwar/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;
}

官方头文件:

/******************************************************************************** Project:  neb* @file     CJsonObject.hpp* @brief    Json* @author   bwarliao* @date:    2014-7-16* @note* Modify history:******************************************************************************/#ifndef CJSONOBJECT_HPP_
#define CJSONOBJECT_HPP_#include <stdio.h>
#include <stddef.h>
#include <malloc.h>
#include <errno.h>
#include <unistd.h>
#include <limits.h>
#include <math.h>
#include <float.h>
#include <string>
#include <map>
#include "cJSON.h"namespace neb
{class CJsonObject
{
public:     // method of ordinary json object or json arrayCJsonObject();CJsonObject(const std::string& strJson);CJsonObject(const CJsonObject* pJsonObject);CJsonObject(const CJsonObject& oJsonObject);virtual ~CJsonObject();CJsonObject& operator=(const CJsonObject& oJsonObject);bool operator==(const CJsonObject& oJsonObject) const;bool Parse(const std::string& strJson);void Clear();bool IsEmpty() const;bool IsArray() const;std::string ToString() const;std::string ToFormattedString() const;const std::string& GetErrMsg() const{return(m_strErrMsg);}public:     // method of ordinary json objectbool 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;bool Get(const std::string& strKey, std::string& strValue) const;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;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);bool Delete(const std::string& strKey);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);public:     // method of json arrayint GetArraySize();CJsonObject& operator[](unsigned int uiWhich);std::string operator()(unsigned int uiWhich) const;bool Get(int iWhich, CJsonObject& oJsonObject) const;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);bool Delete(int 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);private:CJsonObject(cJSON* pJsonData);private:cJSON* m_pJsonData;cJSON* m_pExternJsonDataRef;std::string m_strErrMsg;std::map<unsigned int, CJsonObject*> m_mapJsonArrayRef;std::map<std::string, CJsonObject*> m_mapJsonObjectRef;
};}#endif /* CJSONHELPER_HPP_ */

二、读取json文件到字符串流,然后通过CJsonObject库读取

#include <fstream>
#include <iostream>
#include <string>
#include <assert.h>
#include "CJsonObject.hpp"#define FILEJSON "test.json"using namespace std;string readFile(string file)
{ifstream infile;infile.open(file.data());   //将文件流对象与文件连接起来 assert(infile.is_open());   //若失败,则输出错误消息,并终止程序运行 string str;char c;while (!infile.eof()){infile >> c;str += c;}infile.close();             //关闭文件输入流 return str;
}
int main()
{int iValue;bool flag;bool a=false;std::string strValue;neb::CJsonObject oJson(readFile(FILEJSON));std::cout << oJson.ToString() << std::endl;oJson["dynamic_loading"][0]["cmd"][0].Replace("cmd", 9999);oJson["dynamic_loading"][0]["cmd"][0].Get("cmd", iValue);std::cout << "iValue = " << iValue << std::endl;ofstream out(FILEJSON);//out << oJson.ToString();//无格式转换out << oJson.ToFormattedString();//有格式转换out.close();
}

三、MFC中使用示例

void CJson::TransJsonRowData(CString strJsonPath)
{std::string  strJsonXmCode = CW2A(strJsonPath.GetString());pwjson::CJsonObject oJson(readFile(strJsonXmCode));int nArraySize = oJson.GetArraySize();std::string str = oJson[0]["111"].ToString();CString strDa = str.c_str();std::string str2 = oJson[0]["222"].ToString();CString strDa2 = str2.c_str();for (int i = 0; i < nArraySize; i++){std::string str1 = oJson[i]["111"].ToFormattedString();CString strALTITUDE = str1.c_str();strALTITUDE.Remove(_T('\"'));std::string str2 = oJson[i]["222"].ToFormattedString();CString strLATITUDE = str2.c_str();}}

四、总结

  • 本文主要介绍引入json库基本使用。
  • 如果觉得文章对你有用处,记得 点赞 收藏 转发 一波哦~

💬 往期优质文章分享

  • C++ QT结合FFmpeg实战开发视频播放器-01环境的安装和项目部署
  • 解决QT问题:运行qmake:Project ERROR: Cannot run compiler ‘cl‘. Output:
  • 解决安装QT后MSVC2015 64bit配置无编译器和调试器问题
  • Qt中的套件提示no complier set in kit和no debugger,出现黄色感叹号问题解决(MSVC2017)
  • Python+selenium 自动化 - 实现自动导入、上传外部文件(不弹出windows窗口)

🚀 优质教程分享 🚀

  • 🎄如果感觉文章看完了不过瘾,可以来我的其他 专栏 看一下哦~
  • 🎄比如以下几个专栏:Python实战微信订餐小程序、Python量化交易实战、C++ QT实战类项目 和 算法学习专栏
  • 🎄可以学习更多的关于C++/Python的相关内容哦!直接点击下面颜色字体就可以跳转啦!
学习路线指引(点击解锁)知识定位人群定位
🧡 Python实战微信订餐小程序 🧡进阶级本课程是python flask+微信小程序的完美结合,从项目搭建到腾讯云部署上线,打造一个全栈订餐系统。
💛Python量化交易实战 💛入门级手把手带你打造一个易扩展、更安全、效率更高的量化交易系统
❤️ C++ QT结合FFmpeg实战开发视频播放器❤️难度偏高分享学习QT成品的视频播放器源码,需要有扎实的C++知识!
💚 游戏爱好者九万人社区💚互助/吹水九万人游戏爱好者社区,聊天互助,白嫖奖品
💙 Python零基础到入门 💙Python初学者针对没有经过系统学习的小伙伴,核心目的就是让我们能够快速学习Python的知识以达到入门

🚀 资料白嫖,温馨提示 🚀

关注下面卡片即刻获取更多编程知识,包括各种语言学习资料,上千套PPT模板和各种游戏源码素材等等资料。更多内容可自行查看哦!

请添加图片描述

http://www.xdnf.cn/news/800767.html

相关文章:

  • 教你找电影
  • Microsoft Visual Studio 2010(vs2010) 中文版安装
  • 磊科linux无线网卡驱动安装步骤,怎么安装磊科nw336无线网卡驱动
  • 一星期总结:U盘量产与USB-CDROM制作及修改晨枫U盘维护V2.0完全攻略
  • WIFI_植入JS【转】
  • C语言编译器(C语言编程软件)完全攻略(第二十三部分:Turbo C 2.0下载地址和安装教程(图解))
  • 磊科全功能路由器上网行为管理配置指南 -- 路由器
  • 帮你找到99%的电子书,这46个免费电子书网站,你还不知道吗?
  • 说说QQ校友与校内网的优势
  • 【科普】黑客,骇客,红客,蓝客,它们有什么区别?
  • Linux系统镜像下载(centOS-7)教程
  • 【discuzx2】forum_index.php文件的分析
  • RATIONAL ROSE 2007详细安装教程(图文版)
  • 春晚小宫女唐奕霖 网友封为最美的年轻董事长
  • 上海前端求职招聘工作交流qq群
  • SnakeYAML序列化反序列化其经典反序列化漏洞利用链讲解(非常详细!!!)
  • 宏基4752g linux驱动下载,宏基4752g显卡驱动
  • 100多个优秀的互联网编程学习平台整理。
  • 2021-08-26小白笔记
  • Linux二进制ELF程序查找symbol过程分析
  • 终端里面常用的转义字符串
  • 销毁机密文件你还在用删的吗?文件粉碎了解一下哈!(附自制工具下载)
  • xmind8 Pro序列号_xmind8pro序列号
  • java笔试题总结与大家分享
  • 光立方原理讲解_初中物理光现象知识点汇总大全
  • 9.100ASK_V853-PRO开发板支持E907小核开发
  • C语言入门--VC++6.0
  • PHP的socket详解
  • 浅析事务脚本和领域模型
  • 网站安全检测:推荐 8 款免费的 Web 安全测试工具