SoFunction
Updated on 2025-03-03

JSON serialization and deserialization and processing methods for structures and enumeration types in C++

In C++ programming, processing JSON data is a common task, especially when data exchange is required with other systems or front-ends.nlohmann::jsonThe library is a powerful and easy-to-use JSON library that allows us to easily serialize and deserialize JSON data in C++. This article will introduce in detail how to use itnlohmann::jsonThe library serializes and deserializes structures and enum types.

1. JSON serialization and deserialization of structures

1. Serialization methodto_json

To convert a structure into a JSON object, we need to define ato_jsonfunction. This function receives anlohmann::jsonReferences and a struct instance and populates the struct's fields into the JSON object.

inline void to_json(nlohmann::json &j, const YourStruct &p)
{
    j = nlohmann::json{
        {"field1", p.field1},
        {"field2", p.field2},
        // Add other fields    };
}

In this example,YourStructIt is a custom structure.field1andfield2is its field. passto_jsonFunctions, we canYourStructConvert instances to JSON objects.

2. Deserialization methodfrom_json

To extract data from a JSON object and populate it into a structure, we need to define afrom_jsonfunction. This function also receives anlohmann::jsonReference and a struct reference and extracts data from the JSON object and assigns to the struct field.

inline void from_json(const nlohmann::json &j, YourStruct &p)
{
    try {
        ("field1").get_to(p.field1);
        ("field2").get_to(p.field2);
        // Add other fields    } catch (const nlohmann::json::exception& e) {
        // Handle parsing errors, such as setting default values ​​or marking errors        p.field1 = default_value1;
        p.field2 = default_value2;
        // Or throw an exception        // throw std::runtime_error("Failed to parse JSON: " + std::string(()));
    }
}

In this example, we usetry-catchblock to catch possible exceptions, such as missing a key in a JSON object. If an exception is caught, we can choose to set the default value or throw the exception.

2. Enumerate type JSON serialization and deserialization

When dealing with JSON serialization and deserialization of enum types, we can useNLOHMANN_JSON_SERIALIZE_ENUMMacros to simplify work.

enum class YourEnum {
    Value1,
    Value2,
    // Add other enum values};
NLOHMANN_JSON_SERIALIZE_ENUM(YourEnum,
                             { { YourEnum::Value1, "Value1" },
                               { YourEnum::Value2, "Value2" },
                               // Add other enum values                             })

In this example, we define an enum typeYourEnumand useNLOHMANN_JSON_SERIALIZE_ENUMMacros define string representations of enum values. so,YourEnum::Value1Will be serialized into a string"Value1",vice versa.

3. Sample code

Suppose we have two structuresRobotMsgandRtdeRecipe, and two enum typesRuntimeStateandRobotModeType. Here is the complete sample code:

#include <nlohmann/>
#include <vector>
#include <string>
#include <stdexcept>
// Introduce the JSON library namespaceusing json = nlohmann::json;
// Enumeration type definition and serializationenum 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" } })
// Structure definition and serialization/deserializationstruct 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", },
        {"level", },
        {"code", },
        {"source", },
        {"args", }
    };
}
inline void from_json(const json &j, RobotMsg &p)
{
    try {
        ("timestamp").get_to();
        ("level").get_to();
        ("code").get_to();
        ("source").get_to();
        ("args").get_to();
    } catch (const json::exception& e) {
        // The parsing is invalid         = -1;
        // Or throw an exception        // throw std::runtime_error("Failed to parse JSON: " + std::string(()));
    }
}

This is the article about JSON serialization and deserialization in C++: processing of structures and enum types. For more related content on C++ JSON serialization and deserialization, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!