In C++ programming, processing JSON data is a common task, especially when data exchange is required with other systems or front-ends.nlohmann::json
The 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::json
The 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_json
function. This function receives anlohmann::json
References 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,YourStruct
It is a custom structure.field1
andfield2
is its field. passto_json
Functions, we canYourStruct
Convert 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_json
function. This function also receives anlohmann::json
Reference 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-catch
block 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_ENUM
Macros 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 typeYourEnum
and useNLOHMANN_JSON_SERIALIZE_ENUM
Macros define string representations of enum values. so,YourEnum::Value1
Will be serialized into a string"Value1"
,vice versa.
3. Sample code
Suppose we have two structuresRobotMsg
andRtdeRecipe
, and two enum typesRuntimeState
andRobotModeType
. 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!