序列化与反序列化"/>
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 序列化与反序列化
发布评论