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 array
    CJsonObject();
    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 object
    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;
    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 array
    int 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库基本使用。
  • 如果觉得文章对你有用处,记得 点赞 收藏 转发 一波哦~

💬 往期优质文章分享

🚀 优质教程分享 🚀

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

🚀 资料白嫖,温馨提示 🚀

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

请添加图片描述

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
由于论坛缺少好用支持且易本身C++版本过低导致很多C++新特性无法使用。本次利用C++11/14的标准以及一些C++知名(RapidJson,Curl)编写支持使用,以至于编程上不会太落后。 C++11/14标准相对于微软类而言与微软无关,可实现跨平台。且其拥有很多高级语法,其效率及稳定性毋庸置疑。如果能直接用标准完成坚决不要重复造轮子。     此次封装了线程、线程池、哈希表(UnOrderedMap)、读写锁、互斥、定时器、计时器、Json、Curl等。其中Json封装于RapidJson,此C++最快的Json,效率高于论坛其他工具几百倍。 Curl为知名Http,很多公司及个人都是首选。     由于易语言5.6版本核心与其他版本不太一样导致静态编译过程中出现一些问题,所以请大家最好不要使用5.6版本。由于使用到了高版本C++所以易语言自带的VC6编译器肯定不能编译, 在此本支持使用了论坛的VS2014编译器,完美实现静态编译,如果你本身有这个编译器也请一定用本次配套的替换使用,否则会出现少情况。     至于编译出来的程序能否支持XP,我想说这是肯定的,具体操作方法请参见压缩包里的说明。 备用地址 :链接:https://pan.baidu.com/s/1gY8Gm_kxMH1GOZiYaZeYZw   提取码:u1hs (里面包含编译器,支持,例程) 文件较大,已包含 编辑所需的链接器
acl 是啥、主要包含哪些功能? acl 工程是一个跨平台(支持LINUX,WIN32,Solaris,MacOS,FreeBSD)的网络通信及服务器编程框架,同时提供更多的实用功能。通过该,用户可以非常容易地编写支持多种模式(多线程、多进程、非阻塞、触发器、UDP方式、协程方式)的服务器程序,WEB 应用程序,数据应用程序。此外,该还提供了常见应用的客户端通信(如:HTTP、SMTP、ICMP、redis、disque、memcache、beanstalk、handler socket),常见流式编解码:XML/JSON/MIME/BASE64/UUCODE/QPCODE/RFC2047 等。 ### 2、acl 支持哪些平台? 目前主要支持 Linux/Windows/Macos/Freebsd/Solaris(x86)。 ### 3、acl 主要包含几个? 主要包括:lib_acl(用 C 语言写的基础)、lib_protocol(用 C 语言写的一些网络应用协议)、lib_acl_cpp(用 C++ 语言编写,封装了 lib_acl/lib_protocol 两个,同时增加更多实用的功能)、 lib_fiber(用 C 语言编写的支持高性能、高并发的网络协程)、lib_rpc(用C++语言编写的封装了 google protobuf 网络)。 ### 4、acl 有哪些外部依赖? lib_acl/lib_protocol/lib_fiber 仅依赖系统基础;lib_acl_cpp 的 db 模块依赖于 mysql 客户端、sqlite ,stream 流模块依赖于 polarssl (该源码附在 acl/resource 目录下),另外,在 UNIX/LINUX 平台下还需要压缩 --- libz (一般 LINUX 会自带该压缩);lib_rpc 依赖于 protobuf 。 ### 5、没有这些第三方 acl 能否使用? 可以。默认情况下,没有这些第三方编译和使用 acl 是没有问题的,只是不能使用 mysql/sqlite/ssl/protobuf 功能。
要在C++使用JSON,你可以选择安装一些流行的开源,如jsoncpp、rapidjson或nlohmann/json。下面是安装这些的一些基本步骤: 1. jsoncpp:这是一个跨平台C++ JSON。你可以从它的GitHub仓(https://github.com/open-source-parsers/jsoncpp)下载源代码。 - 使用以下命令克隆jsoncpp的源代码到本地目录中: ``` git clone https://github.com/open-source-parsers/jsoncpp.git ``` - 进入jsoncpp目录: ``` cd jsoncpp ``` - 创建一个build目录,并进入该目录: ``` mkdir build cd build ``` - 使用CMake生成项目文件: ``` cmake .. ``` - 编译并安装: ``` make sudo make install ``` - 安装完成后,你可以在你的C++项目中使用jsoncpp了。 2. rapidjson:这是一个快速的C++ JSON解析生成器。你可以从它的GitHub仓(https://github.com/Tencent/rapidjson)下载源代码。 - 使用以下命令克隆rapidjson的源代码到本地目录中: ``` git clone https://github.com/Tencent/rapidjson.git ``` - 将rapidjson目录中的`include/rapidjson`目录复制到你的项目中。 - 在你的C++项目中包含rapidjson的头文件即可开始使用。 3. nlohmann/json:这是一个现代化的C++ JSON,可以使用简单的API进行操作。你可以从它的GitHub仓(https://github.com/nlohmann/json)下载源代码。 - 使用以下命令克隆nlohmann/json的源代码到本地目录中: ``` git clone https://github.com/nlohmann/json.git ``` - 将nlohmann/json目录中的`single_include/nlohmann`目录复制到你的项目中。 - 在你的C++项目中包含nlohmann/json的头文件即可开始使用。 这些是一些常用的C++ JSON,你可以根据自己的需求选择合适的使用。安装完成后,你就可以使用这些解析和生成JSON数据了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虚坏叔叔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值