How do I serialize and deserialize data structures in C++?

Serialization and deserialization are crucial processes in C++ for transferring data structures over networks or saving them to files. This involves converting an object into a format that can be easily stored and reconstructed later. Below is a simple example demonstrating how to serialize and deserialize a custom data structure in C++ using JSON as the format.

// Example of serialization and deserialization in C++ #include #include #include #include using json = nlohmann::json; struct Person { std::string name; int age; // Method to serialize the object json toJSON() const { return json{{"name", name}, {"age", age}}; } // Method to deserialize the object static Person fromJSON(const json& j) { Person p; j.at("name").get_to(p.name); j.at("age").get_to(p.age); return p; } }; int main() { // Create a Person object Person person{"John Doe", 30}; // Serialize the object to JSON json j = person.toJSON(); std::ofstream file("person.json"); file << j.dump(4); // Write pretty JSON to the file file.close(); // Deserialize the object from JSON std::ifstream inputFile("person.json"); json j2; inputFile >> j2; Person newPerson = Person::fromJSON(j2); std::cout << "Name: " << newPerson.name << ", Age: " << newPerson.age << std::endl; return 0; }

Serialization Deserialization C++ JSON Data Structures Nlohmann/json