ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

序列化 与 反序列化 解读

序列化 与 反序列化 解读 前言做工具开发的小伙伴对序列化和反序列化应该很熟悉几乎每天打交道。本文我们一起入个门。目录一、概念二、为什么需要序列化三、代码示例一、概念序列化是这样一个过程将内存中的数据或对象转化为可以存储或传输的格式如 字节流、XML、JSON。反序列化顾名思义是反过来的过程将字节流还原为内存中的真实数据或对象。我们可以打一个比方你在网上买东西所有的东西都被打包好打包成一个大包裹塞进车厢进行运输。这可以粗暴理解为序列化将快递打包成可运输的状态。送到快递分拣站后将大包裹拆分通过菜鸟驿站将一个个快递送到客户手里。这可以理解为反序列化将打包的快递还原回去。二、为什么需要序列化如果你想把这台机器上的文件或数据送到另一台机器上它们之间无法通过当前内存直接交互必须将这台机器上运行的数据或对象转化为字节流然后通过网络的形式传输到另一台机器。所以我们需要序列化。假如有一个正在运行的程序内存中有很多对象或数据而这些内存中的数据在程序退出后就消失了。如果你想将这些运行中的数据保存下来就必须将它们转化为可以存储的形式JSON、二进制写入磁盘。所以我们需要序列化。三、代码示例1二进制序列化#include iostream #include vector #include cstring struct Point { float x, y; int id; }; // 序列化对象 → 字节数组 std::vectoruint8_t serialize(const Point p) { std::vectoruint8_t buf(sizeof(Point)); std::memcpy(buf.data(), p, sizeof(Point)); return buf; } // 反序列化字节数组 → 对象 Point deserialize(const std::vectoruint8_t buf) { Point p; std::memcpy(p, buf.data(), sizeof(Point)); return p; } int main() { Point original{3.14f, 2.72f, 22}; auto bytes serialize(original); // 序列化 Point restored deserialize(bytes); // 反序列化 std::cout restored.x , restored.y , restored.id \n; return 0; }2JSON#include nlohmann/json.hpp using json nlohmann::json; struct Config { std::string host; int port; }; // 序列化 Config cfg{127.0.0.1, 8080}; json j {{host, cfg.host}, {port, cfg.port}}; std::string text j.dump(); // → {host:127.0.0.1,port:8080} // 反序列化 json parsed json::parse(text); Config restored{parsed[host], parsed[port]};3Protobuf// person.proto syntax proto3; message Person { string name 1; int32 age 2; repeated string emails 3; }#include person.pb.h // 序列化 Person p; p.set_name(Alice); p.set_age(30); p.add_emails(aliceexample.com); std::string bytes; p.SerializeToString(bytes); // → 紧凑二进制 // 反序列化 Person restored; restored.ParseFromString(bytes); std::cout restored.name() \n;
返回列表