msgpack序列化与反序列化

阅读更多

最近想找个二进制序列化框架把对象存起来或者放到缓存里,首先排除了protobuf和thrift, 因为这两个都要写数据定义文件太烦,后来发现msgpack好像很不错的样子,决定试试

 

1.材料

msgpack-0.6.12.jar

2.先定义两个对象

package test.magpack;

import org.msgpack.annotation.Message;

@Message
public class Message2 {

	public Message2(){
		
	}
	
	public Message2(String name){
		this.name = name;
	}
	
	public String name;
	
}

 

package test.magpack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.msgpack.annotation.Message;

@Message // Annotation
public class MyMessage {
	public String name;
    public double version;
    public List list = new ArrayList();
    public Map map = new HashMap();
    public List list2 = new ArrayList();
    public Map map2 = new HashMap();
    public Message2 message;
}

 

3. 测试序列化与反序列化对象

public static void main(String[] args) throws IOException {
		System.setProperty("msgpack.dynamic-codegen.enabled", "false");
		
		MyMessage src = new MyMessage();
        src.name = "msgpack";
        src.version = 0.6;
        src.list.add("1111");
        src.list.add("2222");
        src.map.put("a", "aaaa");
        src.map.put("b", "bbbb");
        src.message = new Message2("=============");
        src.list2.add(new Message2("sssss"));
        src.list2.add(new Message2("ffffff"));
        src.map2.put("aa", new Message2("xxxx"));
        src.map2.put("bb", new Message2("zzzz"));

        MessagePack msgpack = new MessagePack();
        
        // Serialize
        byte[] bytes = msgpack.write(src);
        
        System.out.println(bytes.length);
        
        // Deserialize
        MyMessage dst = msgpack.read(bytes, MyMessage.class);

        System.out.println(dst.name);
        System.out.println(dst.version);
        System.out.println(dst.list);
        System.out.println(dst.map);
        System.out.println(dst.message.name);
        System.out.println(dst.list2);
        System.out.println(dst.map2);
	}

 

这个java的msgpack实现对 对象的嵌套和泛型,list, map都支持, 很好用

 

 

 

  • msgpack-0.6.12.jar (276.7 KB)
  • 下载次数: 46

你可能感兴趣的:(msgpack序列化与反序列化)