iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >C++JSON库CJsonObject详解(轻量简单好用)
  • 921
分享到

C++JSON库CJsonObject详解(轻量简单好用)

2024-04-02 19:04:59 921人浏览 八月长安
摘要

1. JSON概述 jsON: javascript 对象表示法( JavaScript Object Notation) 。是一种轻量级的数据交换格式。 它基于ECMAScript

1. JSON概述

jsON: javascript 对象表示法( JavaScript Object Notation) 。是一种轻量级的数据交换格式。 它基于ECMAScript的一个子集。许多编程语言都很容易找到JSON 解析器和 JSON 库。 JSON 文本格式在语法上与创建 JavaScript 对象的代码相同。不同语言的不同json库对json标准的支持不尽相同,为了能让尽可能多的json库都能正常解析和生成json,定义JSON的规范很重要,推荐一个JSON规范《JSON风格指南》。

2. 常用C&c++ JSON库

常用且知名度较高的C&C++的JSON库有cJSON、json-c、JsonCpp等,腾讯员工开源的一个RapidJSON以高性能著称。C&C++的JSON库比较见RapidJSON作者的比较nativejson-benchmark。

3. 非常简单易用的CJsonObject

CJsonObject是基于cJSON全新开发一个C++版的JSON库,CJsonObject的最大优势是轻量(只有4个文件,拷贝到自己代码里即可,无须编译成库,且跨平台和编译器)、简单好用,开发效率极高,对多层嵌套json的读取和生成使用非常简单(大部分json解析库如果要访问多层嵌套json的最里层非常麻烦)。我一直使用的json库是一个较老版本的cJSON,cJSON的好处是简单易用,而且只有两个文件,直接复制到自己的代码中就可以用。cJSON也有一个非常容易让初用者头痛的地方,一不小心就造成内存泄漏了。为此,我基于cJSON封装了一个C++版的CJsonObject,该库比cJSON更简单易用,且只要不是有意不释放内存就不会发生内存泄漏。用CJsonObject的好处在于完全不用文档,看完Demo马上就会用,不明白的看一下头文件就知道,所有函数都十分通俗易懂,最为关键的一点是解析JSON和生成JSON的编码效率非常高。当然,毕竟是经过cJSON封装而来,效率会略低于cJSON,cJSON不支持的CJsonObject也不支持。个人认为,既然已经选了json,那一点点的解析性能差异就不重要了,如果追求性能可以选protobuf。CJsonObject在我最近5年做过的8个项目中广泛应用。CJsonObject非常简单易用,且表现稳定,2018年5月我把它开源https://GitHub.com/Bwar/CJsonObject,并将持续维护。

来看看CJsonObject是如何简单易用:

demo.cpp:


#include <string>
#include <iOStream>
#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;
}

Demo执行结果:


[bwar@nebula demo]$ ./CJsonObjectTest
{"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":[]}]}
-------------------------------------------------------------------
neb::CmdUserLogout
iValue = 2001
strValue = im/user/login
-------------------------------------------------------------------
{"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":[]}],"depend":{"nebula":"https://github.com/Bwar/Nebula","bootstrap":["BEACON","LOGIC","LOGGER","INTERFACE","ACCESS"]}}
-------------------------------------------------------------------
{
    "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":   []
        }],
    "depend":   {
        "nebula":   "https://github.com/Bwar/Nebula",
        "bootstrap":    ["BEACON", "LOGIC", "LOGGER", "INTERFACE", "ACCESS"]
    }
}

再来看看头文件,一看就知道如何使用:




#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 

如果觉得CJsonObject不错,别忘了给个star,谢谢。

 

到此这篇关于C++JSON库CJsonObject详解(轻量简单好用)的文章就介绍到这了,更多相关C++JSON库CJsonObject内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: C++JSON库CJsonObject详解(轻量简单好用)

本文链接: https://www.lsjlt.com/news/124741.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • C++JSON库CJsonObject详解(轻量简单好用)
    1. JSON概述 JSON: JavaScript 对象表示法( JavaScript Object Notation) 。是一种轻量级的数据交换格式。 它基于ECMAScript...
    99+
    2024-04-02
  • 简单好用的Adapter---ArrayAdapter详解
    拖延症最可怕的地方就是:就算自己这边没有拖延,但对方也会拖延,进而导致自己这边也开始拖延起来!现在这个项目我这边已经是完工了,但是对方迟迟没有搞定,导致整个项目无法提交。这就是拖延症的可怕:我们不仅是与自己的拖延症作战,而是与所有有关人士的...
    99+
    2023-05-30
    android adapter ---ar
  • Python中最好用的json库orjson用法详解
    目录1 简介2 orjson常用方法2.1 序列化2.2 反序列化2.3 丰富的option选项2.4 针对dataclass、datetime添加自定义处理策略总结1 简介 大家好...
    99+
    2024-04-02
  • C语言goto语句简单使用详解
    简单介绍 C语言中提供了可以随意滥用的 goto语句和标记跳转的标号。从理论上 goto语句是没有必要的,实践中没有goto语句也可以很容易的写出代码。但是某些场合下goto语句还是...
    99+
    2024-04-02
  • 详解利用C语言如何实现简单的内存池
    前言 在编程过程中,尤其是对于C语言开发者,其实编程就是在使用内存,不停地变化内存中的数据。当我们想开辟一片新的内存使用时,就会使用malloc实现。但是通过查阅很多资料,发现频繁的...
    99+
    2024-04-02
  • 如何利用MySQL和C++开发一个简单的批量解压功能
    如何利用MySQL和C++开发一个简单的批量解压功能概述:在现代计算机领域,文件的解压常常是一个重要功能,尤其当需要批量解压大量文件时。本文将介绍如何利用MySQL和C++开发一个简单的批量解压功能,并提供具体的代码示例。准备工作在开始之前...
    99+
    2023-10-22
    MySQL C++ 批量解压功能
  • 阿里云轻量应用服务器:简单高效的云端应用托管解决方案
    1. 什么是阿里云轻量应用服务器? 阿里云轻量应用服务器(Alibaba Cloud Lightweight Application Server)是一种简单高效的云端应用托管解决方案。它提供了轻量级的计算资源和完整的应用运行环境,适用于...
    99+
    2023-10-27
    高效 阿里 云端
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作