为了序列化原生的容器对象例如 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*/@Testpublic void testMessagePack6Template() {logger.debug("MessagePack6Template for Template");MessagePack msgpack = new MessagePack();try {// Create templates for serializing/deserializing List and Map objectsTemplate<List<String>> listTmpl = tList(TString);Template<Map<String, String>> mapTmpl = tMap(TString, TString);//// Serialization//ByteArrayOutputStream out = new ByteArrayOutputStream();Packer packer = msgpack.createPacker(out);// Serialize List objectList<String> list = new ArrayList<String>();list.add("msgpack");list.add("for");list.add("java");packer.write(list); // List object// Serialize Map objectMap<String, String> map = new HashMap<String, String>();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 objectList<String> dstList = unpacker.read(listTmpl);// to Map objectMap<String, String> dstMap = unpacker.read(mapTmpl);} catch (Exception ex) {logger.error("MessagePack Serialization And Deserialization error", ex);}} }
https://www.cwiki.us/display/Serialization/QuickStart+For+MessagePack+Java+0.6.X