How do I serialize and deserialize std::any in C++?

Serialization and deserialization of `std::any` in C++ can be achieved by utilizing a combination of type information and stream manipulation. The `std::any` type allows you to store values of any type and can be serialized and deserialized by extracting the contained value and converting it to a format suitable for storage, such as JSON or binary.

Below is an example of how to serialize and deserialize `std::any` using JSON as the intermediary format. For this example, we'll use the `nlohmann/json` library for ease of JSON manipulation.

#include #include #include // Using nlohmann::json for serialization and deserialization using json = nlohmann::json; // Function to serialize std::any json serialize(const std::any& data) { if (data.type() == typeid(int)) { return json{ {"type", "int"}, {"value", std::any_cast(data)} }; } else if (data.type() == typeid(double)) { return json{ {"type", "double"}, {"value", std::any_cast(data)} }; } else if (data.type() == typeid(std::string)) { return json{ {"type", "string"}, {"value", std::any_cast<:string>(data)} }; } throw std::runtime_error("Unsupported type"); } // Function to deserialize std::any from json std::any deserialize(const json& j) { std::string type = j.at("type"); if (type == "int") { return j.at("value").get(); } else if (type == "double") { return j.at("value").get(); } else if (type == "string") { return j.at("value").get<:string>(); } throw std::runtime_error("Unsupported type"); } int main() { std::any myData = 42; // Can be int, double or std::string // Serialization json serializedData = serialize(myData); std::cout << "Serialized: " << serializedData.dump() << std::endl; // Deserialization std::any deserializedData = deserialize(serializedData); std::cout << "Deserialized Value: " << std::any_cast(deserializedData) << std::endl; return 0; }

C++ std::any serialization deserialization JSON nlohmann/json