msgpack 序列化与反序列化

编程入门 行业动态 更新时间:2024-10-27 01:30:12

msgpack <a href=https://www.elefans.com/category/jswz/34/1769864.html style=序列化与反序列化"/>

msgpack 序列化与反序列化

1.msgpack 安装

git clone git://github.com/msgpack/msgpack-c.git
cmake .
sudo make install

msgpack 是一种高效的二进制序列化格式,它的功能类似 json ,可以在多种语言之间交换数据。但是它的速度更快,体积也更小,支持几乎所有的主流程序语言。

2.程序实例

序列以及反序列化数据

#include <msgpack.hpp>
#include <string>
#include <iostream>
#include <sstream>int main()
{msgpack::type::tuple<bool, char, std::string> src(true, 'i', "shiyanlou");std::stringstream buffer;// 序列化msgpack::pack(buffer, src);std::string str(buffer.str());// 反序列化msgpack::object_handle oh =    msgpack::unpack(str.data(), str.size());msgpack::object deserialized = oh.get();std::cout << deserialized << std::endl;// 两种把 msgpack::object_handle 转化为 msgpack::type::tuple 的方法msgpack::type::tuple<bool, char, std::string> dst;deserialized.convert(dst);msgpack::type::tuple<bool, char, std::string> dst2 =    deserialized.as<msgpack::type::tuple<bool, char, std::string> >();return 0;
}

自定义类型的序列以及反序列化

#include <iostream>
#include <string>
#include <sstream>
#include <msgpack.hpp>class person {
public://person() :name("") { age = 0; id = 0; };person(int id_ = 0, std::string name_ = "", int age_ = 0) :name(name_) { age = age_; id = id_; };int id;std::string name;int age;MSGPACK_DEFINE(id, name, age); // 申明这个类需要序列化void disply() {std::cout << id << " " << name << " " << age << std::endl;};
};void test() {person src(1, "tom", 20 );std::stringstream buffer;msgpack::pack(buffer, src); // 将自定义类序列化std::string str(buffer.str());msgpack::object_handle oh = msgpack::unpack(str.data(), str.size()); // 反序列化msgpack::object deserialized = oh.get();person dst = deserialized.as<person>(); // 得到类的实例dst.disply(); // 调用类的方法}int main()
{test();return 0;
}

更多推荐

msgpack 序列化与反序列化

本文发布于:2023-07-28 19:54:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293542.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   化与   序列化   msgpack

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!