为了序列化原生的容器对象例如 List 和Map对象,你必须使用Template。
Template 对象是 serializer 和 deserializer 的配对。例如,为了序列化一个List对象,在List对象中Integer对象为元素,你可以使用下面的方法来创建一个模板对象(Template object)。
Template listTmpl = Templates.tList(Templates.TInteger);
类 tList,TInteger是静态方法,字段为Templates。
一个 List和Map对象的用例如下显示:
本代码可以在https://github.com/cwiki-us-demo/messagepack-6-demo-java/blob/master/src/test/java/com/insight/demo/msgpack/MessagePack6Template.java中查看。
package com.insight.demo.msgpack;
import org.junit.Test;
import org.msgpack.MessagePack;
import org.msgpack.packer.Packer;
import org.msgpack.template.Template;
import org.msgpack.unpacker.Unpacker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.msgpack.template.Templates.*;
/**
* MessagePack6Template
*
* @author yhu
*/
public class MessagePack6Template {
final Logger logger = LoggerFactory.getLogger(MessagePack6Template.class);
/**
* Test MessagePack6Template
*/
@Test
public void testMessagePack6Template() {
logger.debug("MessagePack6Template for Template");
MessagePack msgpack = new MessagePack();
try {
// Create templates for serializing/deserializing List and Map objects
Template> listTmpl = tList(TString);
Template
//
// Serialization
//
ByteArrayOutputStream out = new ByteArrayOutputStream();
Packer packer = msgpack.createPacker(out);
// Serialize List object
List
list.add("msgpack");
list.add("for");
list.add("java");
packer.write(list); // List object
// Serialize Map object
Map
map.put("sadayuki", "furuhashi");
map.put("muga", "nishizawa");
packer.write(map); // Map object
//
// Deserialization
//
byte[] bytes = out.toByteArray();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
Unpacker unpacker = msgpack.createUnpacker(in);
// to List object
List
// to Map object
Map
} catch (Exception ex) {
logger.error("MessagePack Serialization And Deserialization error", ex);
}
}
}
https://www.cwiki.us/display/Serialization/QuickStart+For+MessagePack+Java+0.6.X