c++好用的json解析类源码分享及简单使用

简介: c++好用的json解析类源码分享及简单使用

json数据解析,这是很常见的功能需求。c语言里有有名的cJSON库可用,当然c++里也可以直接用或者做个封装。但是可用不代表着就好用。有些情况下我们拿c++做开发而不是选择c,不就是为了开发上高效,维护上方便,可以做一些大项目么。


这里分享下封装的c++的好用的json解析库,不是原创。从OpenHarmony源码里摘出来的,所以可以放心用。直接学习优秀的开源项目代码好处多多,有时候是看书本学不来的。


摘自开源鸿蒙系统源码的JS UI框架代码。开源鸿蒙应用使用js开发,运行效率不用担心是因为框架使用的还是c++。


c++自从c++11标准之后真是焕然一新,使用变得简单且更好用了。从这个json解析源码里就能看出来一些:如使用了auto,lambda,智能指针等,智能指针的使用使得不用担心什么时候new的忘了释放掉这个心智负担,后续想new的地方要优先考虑使用智能指针。


条款21里有一条:尽量使用std::make_unique和std::make_shared而不直接使用new(《Effective Modern C++》一书)。


c++需要注意的地方之一就是对内存的管理,动态内存的使用经常会出现内存泄漏,或者产生引用非法内存的指针。


新的标准库提供了两种智能指针类型来管理动态对象:


(1)shared_ptr 允许多个指针指向同一个对象


(2)unique_ptr 独占所指向的对象


定义在memory头文件中,他们的作用在于会自动释放所指向的对象。


unique_ptr 是 C++ 11 提供的用于防止内存泄漏的智能指针中的一种实现,独享被管理对象指针所有权的智能指针。unique_ptr对象包装一个原始指针,并负责其生命周期。当该对象被销毁时,会在其析构函数中删除关联的原始指针。


unique_ptr具有->和*运算符重载符,因此它可以像普通指针一样使用。


unique_ptr不能直接复制,必须使用std::move()转移其管理的指针,转移后原 unique_ptr 为空。


unique_ptr支持的操作(C++ Primer Fifth Edition 中文版一书):



这个json解析类的源码里,至少用到了c++14及以上的特性(从std::make_unique这个智能指针可看出),若你的工具链版本低可能不行。


gcc工具链从4.7.0之后开始支持c++11标准。GCC 4.8.1完全支持c++11核心部分,对应的glibc为2.17,gcc 4.9支持c++11正则表达式。gcc从哪个版本之后开始支持c++14?好像是GCC v6.1之后。


源码文件路径:code-v3.0-LTS\OpenHarmony\foundation\ace\ace_engine\frameworks\base\json


json_util.cpp和json_util.h


其实还是对cJSON库的封装:


#include "base/json/json_util.h"
#include "cJSON.h"
namespace OHOS::Ace {
JsonValue::JsonValue(JsonObject* object) : object_(object) {}
JsonValue::JsonValue(JsonObject* object, bool isRoot) : object_(object), isRoot_(isRoot) {}
JsonValue::~JsonValue()
{
    if (object_ != nullptr && isRoot_) {
        cJSON_Delete(object_);
    }
    object_ = nullptr;
}
bool JsonValue::IsBool() const
{
    return cJSON_IsBool(object_);
}
bool JsonValue::IsNumber() const
{
    return cJSON_IsNumber(object_);
}
bool JsonValue::IsString() const
{
    return cJSON_IsString(object_);
}
bool JsonValue::IsArray() const
{
    return cJSON_IsArray(object_);
}
bool JsonValue::IsObject() const
{
    return cJSON_IsObject(object_);
}
bool JsonValue::IsValid() const
{
    return (object_ != nullptr) && !cJSON_IsInvalid(object_);
}
bool JsonValue::IsNull() const
{
    return (object_ == nullptr) || cJSON_IsNull(object_);
}
bool JsonValue::Contains(const std::string& key) const
{
    return cJSON_HasObjectItem(object_, key.c_str());
}
bool JsonValue::GetBool() const
{
    return cJSON_IsTrue(object_) != 0;
}
bool JsonValue::GetBool(const std::string& key, bool defaultValue) const
{
    if (Contains(key) && GetValue(key)->IsBool()) {
        return GetValue(key)->GetBool();
    }
    return defaultValue;
}
int32_t JsonValue::GetInt() const
{
    return static_cast<int32_t>((object_ == nullptr) ? 0 : object_->valuedouble);
}
uint32_t JsonValue::GetUInt() const
{
    return static_cast<uint32_t>((object_ == nullptr) ? 0 : object_->valuedouble);
}
double JsonValue::GetDouble() const
{
    return (object_ == nullptr) ? 0.0 : object_->valuedouble;
}
double JsonValue::GetDouble(const std::string& key, double defaultVal) const
{
    auto value = GetValue(key);
    if (value && value->IsNumber()) {
        return value->GetDouble();
    }
    return defaultVal;
}
std::string JsonValue::GetString() const
{
    return ((object_ == nullptr) || (object_->valuestring == nullptr)) ? "" : std::string(object_->valuestring);
}
std::unique_ptr<JsonValue> JsonValue::GetNext() const
{
    if (object_ == nullptr) {
        return std::make_unique<JsonValue>(nullptr);
    }
    return std::make_unique<JsonValue>(object_->next);
}
std::unique_ptr<JsonValue> JsonValue::GetChild() const
{
    if (object_ == nullptr) {
        return std::make_unique<JsonValue>(nullptr);
    }
    return std::make_unique<JsonValue>(object_->child);
}
std::string JsonValue::GetKey() const
{
    return ((object_ == nullptr) || (object_->string == nullptr)) ? "" : std::string(object_->string);
}
std::unique_ptr<JsonValue> JsonValue::GetValue(const std::string& key) const
{
    return std::make_unique<JsonValue>(cJSON_GetObjectItem(object_, key.c_str()));
}
std::unique_ptr<JsonValue> JsonValue::GetObject(const std::string& key) const
{
    if (Contains(key) && GetValue(key)->IsObject()) {
        return GetValue(key);
    }
    return std::make_unique<JsonValue>();
}
int32_t JsonValue::GetArraySize() const
{
    return cJSON_GetArraySize(object_);
}
std::unique_ptr<JsonValue> JsonValue::GetArrayItem(int32_t index) const
{
    return std::make_unique<JsonValue>(cJSON_GetArrayItem(object_, index));
}
bool JsonValue::Put(const char* key, const char* value)
{
    if (!value || !key) {
        return false;
    }
    cJSON* child = cJSON_CreateString(value);
    if (child == nullptr) {
        return false;
    }
    cJSON_AddItemToObject(object_, key, child);
    return true;
}
const JsonObject* JsonValue::GetJsonObject() const
{
    return object_;
}
bool JsonValue::Put(const char* key, const std::unique_ptr<JsonValue>& value)
{
    if (!value || !key) {
        return false;
    }
    cJSON* jsonObject = cJSON_Duplicate(value->GetJsonObject(), true);
    if (jsonObject == nullptr) {
        return false;
    }
    cJSON_AddItemToObject(object_, key, jsonObject);
    return true;
}
// add item to array
bool JsonValue::Put(const std::unique_ptr<JsonValue>& value)
{
    if (!value) {
        return false;
    }
    cJSON* jsonObject = cJSON_Duplicate(value->GetJsonObject(), true);
    if (jsonObject == nullptr) {
        return false;
    }
    cJSON_AddItemToArray(object_, jsonObject);
    return true;
}
bool JsonValue::Put(const char* key, size_t value)
{
    if (key == nullptr) {
        return false;
    }
    cJSON* child = cJSON_CreateNumber(static_cast<double>(value));
    if (child == nullptr) {
        return false;
    }
    cJSON_AddItemToObject(object_, key, child);
    return true;
}
bool JsonValue::Put(const char* key, int32_t value)
{
    if (key == nullptr) {
        return false;
    }
    cJSON* child = cJSON_CreateNumber(static_cast<double>(value));
    if (child == nullptr) {
        return false;
    }
    cJSON_AddItemToObject(object_, key, child);
    return true;
}
bool JsonValue::Put(const char* key, double value)
{
    if (key == nullptr) {
        return false;
    }
    cJSON* child = cJSON_CreateNumber(value);
    if (child == nullptr) {
        return false;
    }
    cJSON_AddItemToObject(object_, key, child);
    return true;
}
bool JsonValue::Put(const char* key, bool value)
{
    if (key == nullptr) {
        return false;
    }
    cJSON* child = cJSON_CreateBool(value);
    if (child == nullptr) {
        return false;
    }
    cJSON_AddItemToObject(object_, key, child);
    return true;
}
bool JsonValue::Replace(const char* key, const char* value)
{
    if ((value == nullptr) || (key == nullptr)) {
        return false;
    }
    cJSON* child = cJSON_CreateString(value);
    if (child == nullptr) {
        return false;
    }
    if (!cJSON_ReplaceItemInObject(object_, key, child)) {
        cJSON_Delete(child);
        return false;
    }
    return true;
}
bool JsonValue::Replace(const char* key, int32_t value)
{
    if (key == nullptr) {
        return false;
    }
    cJSON* child = cJSON_CreateNumber(static_cast<double>(value));
    if (child == nullptr) {
        return false;
    }
    if (!cJSON_ReplaceItemInObject(object_, key, child)) {
        cJSON_Delete(child);
        return false;
    }
    return true;
}
bool JsonValue::Replace(const char* key, const std::unique_ptr<JsonValue>& value)
{
    if ((value == nullptr) || (key == nullptr)) {
        return false;
    }
    cJSON* jsonObject = cJSON_Duplicate(value->GetJsonObject(), true);
    if (jsonObject == nullptr) {
        return false;
    }
    if (!cJSON_ReplaceItemInObject(object_, key, jsonObject)) {
        cJSON_Delete(jsonObject);
        return false;
    }
    return true;
}
bool JsonValue::Delete(const char* key)
{
    if (key == nullptr) {
        return false;
    }
    cJSON_DeleteItemFromObject(object_, key);
    return true;
}
std::string JsonValue::ToString()
{
    std::string result;
    if (!object_) {
        return result;
    }
    // It is null-terminated.
    char* unformatted = cJSON_PrintUnformatted(object_);
    if (unformatted != nullptr) {
        result = unformatted;
        cJSON_free(unformatted);
    }
    return result;
}
std::string JsonValue::GetString(const std::string& key, const std::string& defaultVal) const
{
    auto value = GetValue(key);
    if (value && value->IsString()) {
        return value->GetString();
    }
    return defaultVal;
}
int32_t JsonValue::GetInt(const std::string& key, int32_t defaultVal) const
{
    auto value = GetValue(key);
    if (value && value->IsNumber()) {
        return value->GetInt();
    }
    return defaultVal;
}
uint32_t JsonValue::GetUInt(const std::string& key, uint32_t defaultVal) const
{
    auto value = GetValue(key);
    if (value && value->IsNumber()) {
        return value->GetUInt();
    }
    return defaultVal;
}
std::unique_ptr<JsonValue> JsonUtil::ParseJsonData(const char* data, const char** parseEnd)
{
    return std::make_unique<JsonValue>(cJSON_ParseWithOpts(data, parseEnd, true), true);
}
std::unique_ptr<JsonValue> JsonUtil::ParseJsonString(const std::string& content, const char** parseEnd)
{
    return ParseJsonData(content.c_str(), parseEnd);
}
std::unique_ptr<JsonValue> JsonUtil::Create(bool isRoot)
{
    return std::make_unique<JsonValue>(cJSON_CreateObject(), isRoot);
}
std::unique_ptr<JsonValue> JsonUtil::CreateArray(bool isRoot)
{
    return std::make_unique<JsonValue>(cJSON_CreateArray(), isRoot);
}
} // namespace OHOS::Ace


#ifndef FOUNDATION_ACE_FRAMEWORKS_BASE_JSON_JSON_UTIL_H
#define FOUNDATION_ACE_FRAMEWORKS_BASE_JSON_JSON_UTIL_H
#include <memory>
#include <string>
#include "base/utils/macros.h"
struct cJSON;
namespace OHOS::Ace {
using JsonObject = cJSON;
class ACE_FORCE_EXPORT JsonValue final {
public:
    JsonValue() = default;
    explicit JsonValue(JsonObject* object);
    JsonValue(JsonObject* object, bool isRoot);
    ~JsonValue();
    // check functions
    bool IsBool() const;
    bool IsNumber() const;
    bool IsString() const;
    bool IsArray() const;
    bool IsObject() const;
    bool IsValid() const;
    bool IsNull() const;
    bool Contains(const std::string& key) const;
    // get functions
    bool GetBool() const;
    bool GetBool(const std::string& key, bool defaultValue = false) const;
    int32_t GetInt() const;
    int32_t GetInt(const std::string& key, int32_t defaultVal = 0) const;
    uint32_t GetUInt() const;
    uint32_t GetUInt(const std::string& key, uint32_t defaultVal = 0) const;
    double GetDouble() const;
    double GetDouble(const std::string& key, double defaultVal = 0.0) const;
    std::string GetString() const;
    std::string GetString(const std::string& key, const std::string& defaultVal = "") const;
    std::unique_ptr<JsonValue> GetNext() const;
    std::unique_ptr<JsonValue> GetChild() const;
    std::string GetKey() const;
    std::unique_ptr<JsonValue> GetValue(const std::string& key) const;
    std::unique_ptr<JsonValue> GetObject(const std::string& key) const;
    int32_t GetArraySize() const;
    std::unique_ptr<JsonValue> GetArrayItem(int32_t index) const;
    const JsonObject* GetJsonObject() const;
    // put functions
    bool Put(const char* key, const char* value);
    bool Put(const char* key, size_t value);
    bool Put(const char* key, int32_t value);
    bool Put(const char* key, double value);
    bool Put(const char* key, bool value);
    bool Put(const char* key, const std::unique_ptr<JsonValue>& value);
    bool Put(const std::unique_ptr<JsonValue>& value);
    // replace functions
    bool Replace(const char* key, const char* value);
    bool Replace(const char* key, int32_t value);
    bool Replace(const char* key, const std::unique_ptr<JsonValue>& value);
    // delete functions
    bool Delete(const char* key);
    // serialize
    std::string ToString();
private:
    JsonObject* object_ = nullptr;
    bool isRoot_ = false;
};
class ACE_EXPORT JsonUtil final {
public:
    JsonUtil() = delete;
    ~JsonUtil() = delete;
    static std::unique_ptr<JsonValue> ParseJsonData(const char* data, const char** parseEnd = nullptr);
    static std::unique_ptr<JsonValue> ParseJsonString(const std::string& content, const char** parseEnd = nullptr);
    static std::unique_ptr<JsonValue> Create(bool isRoot);
    static std::unique_ptr<JsonValue> CreateArray(bool isRoot);
};
} // namespace OHOS::Ace
#endif // FOUNDATION_ACE_FRAMEWORKS_BASE_JSON_JSON_UTIL_H


使用方法,如以下代码片段,定义了一个右值引用actionEventHandler ,使用了lambda表达式写法,c++新语法用着就是美:


// action event hadnler
    auto&& actionEventHandler = [this] (const std::string& action) {
        LOGI("on Action called to event handler");
        auto eventAction = JsonUtil::ParseJsonString(action);
        auto bundleName = eventAction->GetValue("bundleName");
        auto abilityName = eventAction->GetValue("abilityName");
        auto params = eventAction->GetValue("params");
        auto bundle = bundleName->GetString();
        auto ability = abilityName->GetString();
        LOGI("bundle:%{public}s ability:%{public}s, params:%{public}s",
            bundle.c_str(), ability.c_str(), params->GetString().c_str());
        if (bundle.empty() || ability.empty()) {
            LOGE("action ability or bundle is empty");
            return;
        }
        AAFwk::Want want;
        want.SetElementName(bundle, ability);
        this->StartAbility(want);
    };



相关文章
|
7月前
|
JSON 中间件 Java
【GoGin】(3)Gin的数据渲染和中间件的使用:数据渲染、返回JSON、浅.JSON()源码、中间件、Next()方法
我们在正常注册中间件时,会打断原有的运行流程,但是你可以在中间件函数内部添加Next()方法,这样可以让原有的运行流程继续执行,当原有的运行流程结束后再回来执行中间件内部的内容。​ c.Writer.WriteHeaderNow()还会写入文本流中。可以看到使用next后,正常执行流程中并没有获得到中间件设置的值。接口还提供了一个可以修改ContentType的方法。判断了传入的状态码是否符合正确的状态码,并返回。在内部封装时,只是标注了不同的render类型。再看一下其他返回的类型;
364 3
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
515 12
|
11月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
275 0
|
11月前
|
存储 编译器 程序员
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
437 0
|
设计模式 安全 C++
【C++进阶】特殊类设计 && 单例模式
通过对特殊类设计和单例模式的深入探讨,我们可以更好地设计和实现复杂的C++程序。特殊类设计提高了代码的安全性和可维护性,而单例模式则确保类的唯一实例性和全局访问性。理解并掌握这些高级设计技巧,对于提升C++编程水平至关重要。
263 16
|
编译器 C++
类和对象(中 )C++
本文详细讲解了C++中的默认成员函数,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载和取地址运算符重载等内容。重点分析了各函数的特点、使用场景及相互关系,如构造函数的主要任务是初始化对象,而非创建空间;析构函数用于清理资源;拷贝构造与赋值运算符的区别在于前者用于创建新对象,后者用于已存在的对象赋值。同时,文章还探讨了运算符重载的规则及其应用场景,并通过实例加深理解。最后强调,若类中存在资源管理,需显式定义拷贝构造和赋值运算符以避免浅拷贝问题。
|
存储 编译器 C++
类和对象(上)(C++)
本篇内容主要讲解了C++中类的相关知识,包括类的定义、实例化及this指针的作用。详细说明了类的定义格式、成员函数默认为inline、访问限定符(public、protected、private)的使用规则,以及class与struct的区别。同时分析了类实例化的概念,对象大小的计算规则和内存对齐原则。最后介绍了this指针的工作机制,解释了成员函数如何通过隐含的this指针区分不同对象的数据。这些知识点帮助我们更好地理解C++中类的封装性和对象的实现原理。
|
编译器 C++
类和对象(下)C++
本内容主要讲解C++中的初始化列表、类型转换、静态成员、友元、内部类、匿名对象及对象拷贝时的编译器优化。初始化列表用于成员变量定义初始化,尤其对引用、const及无默认构造函数的类类型变量至关重要。类型转换中,`explicit`可禁用隐式转换。静态成员属类而非对象,受访问限定符约束。内部类是独立类,可增强封装性。匿名对象生命周期短,常用于临时场景。编译器会优化对象拷贝以提高效率。最后,鼓励大家通过重复练习提升技能!
|
8月前
|
机器学习/深度学习 JSON 监控
淘宝拍立淘按图搜索与商品详情API的JSON数据返回详解
通过调用taobao.item.get接口,获取商品标题、价格、销量、SKU、图片、属性、促销信息等全量数据。
|
7月前
|
JSON API 数据格式
淘宝拍立淘按图搜索API系列,json数据返回
淘宝拍立淘按图搜索API系列通过图像识别技术实现商品搜索功能,调用后返回的JSON数据包含商品标题、图片链接、价格、销量、相似度评分等核心字段,支持分页和详细商品信息展示。以下是该API接口返回的JSON数据示例及详细解析:

推荐镜像

更多
  • DNS