C++ msgpack学习

#include 
#include 
#include 
#include 
#include 

struct Card
{
    std::string color;
    int number;
    Card()
    {
        color = "default";
        number = 0;
    }
    MSGPACK_DEFINE(color, number);
};

struct ThinkCard
{
    int type;
    Card card;
    ThinkCard()
    {
        type = 0;
    }
    MSGPACK_DEFINE(type, card);
};

struct AA
{
    int a = 1;
    int b = 2;
    MSGPACK_DEFINE_ARRAY(a, b);
};

void testMsgpack1()
{
    // -------------------- vector --------------------
    std::vector vec;
    vec.push_back("Hello");
    vec.push_back("MessagePack");

    // pack
    std::stringstream ss;
    msgpack::pack(ss, vec);

    // unpack
    msgpack::object_handle oh = msgpack::unpack(ss.str().data(), ss.str().size());
    msgpack::object obj = oh.get();
    std::cout << obj << std::endl;  //=> ["Hello", "MessagePack"]

    // convert
    std::vector rvec;
    obj.convert(rvec);

    // print
    std::vector::iterator it = rvec.begin();
    for (; it != rvec.end(); ++it )
    {
        std::cout << *it << std::endl;
    }

    // -------------------- int --------------------
    int i{5};

    // pack
    std::stringstream ss2;
    msgpack::pack(ss2, i);

    // unpack
    msgpack::object_handle oh2 = msgpack::unpack(ss2.str().data(), ss2.str().size());
    msgpack::object obj2 = oh2.get();
    std::cout << obj2 <   pker(&sbuf);

// 序列化
    pker.pack_map(3);
    pker.pack(std::string("type"));
    pker.pack(3);
    pker.pack(std::string("ratio"));
    pker.pack(2.15);
    pker.pack(std::string("msg"));
    pker.pack(std::string("hello world"));

// 反序列化
    msgpack::unpacked  unpack;
    msgpack::unpack(unpack, sbuf.data(), sbuf.size());

// 直接输出结果
    msgpack::object  obj = unpack.get();
    std::cout << obj << std::endl;

// 访问具体键值对
//    msgpack::object_kv*  pkv;
//    msgpack::object_kv*  pkv_end;
//    msgpack::object      pk, pv;
//    if(obj.via.map.size > 0)
//    {
//        pkv = obj.via.map.ptr;
//        pkv_end = obj.via.map.ptr + obj.via.map.size;
//
//        do
//        {
//            pk = pkv->key;
//            pv = pkv->val;
//
//            std::cout << pk << ", " << pv << std::endl;
//
//            ++pkv;
//        }
//        while (pkv < pkv_end);
//    }
    if (obj.type == msgpack::type::MAP)
    {
        std::map kv;
        kv = obj.as>();
        for (auto it = kv.begin(); it != kv.end(); ++it)
        {
            std::cout << it->first << ", " << it->second << std::endl;
        }
    }
}

int main()
{
  testMsgpack1();  
  return 0;
}

// g++ test1.cpp -I/home/hp/tools/messagepack/msgpack-c/include
//

你可能感兴趣的:(C++ msgpack学习)