欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++?中的?JSON?序列化和反序列化及結(jié)構(gòu)體與枚舉類型的處理方法

 更新時間:2024年11月08日 12:11:08   作者:極地星光  
在?C++?編程中,處理?JSON?數(shù)據(jù)是一項常見任務(wù),特別是在需要與其他系統(tǒng)或前端進(jìn)行數(shù)據(jù)交換時,本文將詳細(xì)介紹如何使用?nlohmann::json?庫對結(jié)構(gòu)體和枚舉類型進(jìn)行序列化和反序列化,感興趣的朋友一起看看吧

在 C++ 編程中,處理 JSON 數(shù)據(jù)是一項常見任務(wù),特別是在需要與其他系統(tǒng)或前端進(jìn)行數(shù)據(jù)交換時。nlohmann::json 庫是一個功能強(qiáng)大且易于使用的 JSON 庫,它允許我們輕松地在 C++ 中進(jìn)行 JSON 數(shù)據(jù)的序列化和反序列化。本文將詳細(xì)介紹如何使用 nlohmann::json 庫對結(jié)構(gòu)體和枚舉類型進(jìn)行序列化和反序列化。

一、結(jié)構(gòu)體的 JSON 序列化和反序列化

1. 序列化方法 to_json

要將結(jié)構(gòu)體轉(zhuǎn)換為 JSON 對象,我們需要定義一個 to_json 函數(shù)。這個函數(shù)接收一個 nlohmann::json 引用和一個結(jié)構(gòu)體實例,并將結(jié)構(gòu)體的字段填充到 JSON 對象中。

inline void to_json(nlohmann::json &j, const YourStruct &p)
{
    j = nlohmann::json{
        {"field1", p.field1},
        {"field2", p.field2},
        // 添加其他字段
    };
}

在這個例子中,YourStruct 是一個自定義的結(jié)構(gòu)體,field1field2 是它的字段。通過 to_json 函數(shù),我們可以將 YourStruct 實例轉(zhuǎn)換為 JSON 對象。

2. 反序列化方法 from_json

要從 JSON 對象中提取數(shù)據(jù)并填充到結(jié)構(gòu)體中,我們需要定義一個 from_json 函數(shù)。這個函數(shù)同樣接收一個 nlohmann::json 引用和一個結(jié)構(gòu)體引用,并從 JSON 對象中提取數(shù)據(jù)并賦值給結(jié)構(gòu)體的字段。

inline void from_json(const nlohmann::json &j, YourStruct &p)
{
    try {
        j.at("field1").get_to(p.field1);
        j.at("field2").get_to(p.field2);
        // 添加其他字段
    } catch (const nlohmann::json::exception& e) {
        // 處理解析錯誤,例如設(shè)置默認(rèn)值或標(biāo)記錯誤
        p.field1 = default_value1;
        p.field2 = default_value2;
        // 或者拋出異常
        // throw std::runtime_error("Failed to parse JSON: " + std::string(e.what()));
    }
}

在這個例子中,我們使用 try-catch 塊來捕獲可能的異常,例如 JSON 對象中缺少某個鍵。如果捕獲到異常,我們可以選擇設(shè)置默認(rèn)值或拋出異常。

二、枚舉類型的 JSON 序列化和反序列化

處理枚舉類型的 JSON 序列化和反序列化時,我們可以使用 NLOHMANN_JSON_SERIALIZE_ENUM 宏來簡化工作。

enum class YourEnum {
    Value1,
    Value2,
    // 添加其他枚舉值
};
NLOHMANN_JSON_SERIALIZE_ENUM(YourEnum,
                             { { YourEnum::Value1, "Value1" },
                               { YourEnum::Value2, "Value2" },
                               // 添加其他枚舉值
                             })

在這個例子中,我們定義了一個枚舉類型 YourEnum,并使用 NLOHMANN_JSON_SERIALIZE_ENUM 宏來定義枚舉值的字符串表示形式。這樣,YourEnum::Value1 將被序列化為字符串 "Value1",反之亦然。

三、示例代碼

假設(shè)我們有兩個結(jié)構(gòu)體 RobotMsgRtdeRecipe,以及兩個枚舉類型 RuntimeStateRobotModeType。以下是完整的示例代碼:

#include <nlohmann/json.hpp>
#include <vector>
#include <string>
#include <stdexcept>
// 引入 JSON 庫命名空間
using json = nlohmann::json;
// 枚舉類型定義及序列化
enum class RuntimeState {
    Running,
    Retracting,
    Pausing,
    Paused,
    Stopping,
    Stopped,
    Aborting
};
NLOHMANN_JSON_SERIALIZE_ENUM(RuntimeState,
                             { { RuntimeState::Running, "Running" },
                               { RuntimeState::Retracting, "Retracting" },
                               { RuntimeState::Pausing, "Pausing" },
                               { RuntimeState::Paused, "Paused" },
                               { RuntimeState::Stopping, "Stopping" },
                               { RuntimeState::Stopped, "Stopped" },
                               { RuntimeState::Aborting, "Aborting" } })
// 結(jié)構(gòu)體定義及序列化/反序列化
struct RobotMsg {
    int64_t timestamp;
    int level;
    int code;
    std::string source;
    std::vector<std::string> args;
};
inline void to_json(json &j, const RobotMsg &p)
{
    j = json{
        {"timestamp", p.timestamp},
        {"level", p.level},
        {"code", p.code},
        {"source", p.source},
        {"args", p.args}
    };
}
inline void from_json(const json &j, RobotMsg &p)
{
    try {
        j.at("timestamp").get_to(p.timestamp);
        j.at("level").get_to(p.level);
        j.at("code").get_to(p.code);
        j.at("source").get_to(p.source);
        j.at("args").get_to(p.args);
    } catch (const json::exception& e) {
        // 解析無效
        p.code = -1;
        // 或者拋出異常
        // throw std::runtime_error("Failed to parse JSON: " + std::string(e.what()));
    }
}

到此這篇關(guān)于C++ 中的 JSON 序列化和反序列化:結(jié)構(gòu)體與枚舉類型的處理的文章就介紹到這了,更多相關(guān)C++ JSON 序列化和反序列化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論