Skip to content
Taro L. Saito edited this page May 22, 2020 · 20 revisions

Usage

pom.xml

<dependency>
   <groupId>org.msgpack</groupId>
   <artifactId>msgpack-core</artifactId>
   <version>(version)</version>
</dependency>
// Serialize with MessagePacker.
// MessageBufferPacker is an optimized version of MessagePacker for packing data into a byte array
MessageBufferPacker packer = MessagePack.newDefaultBufferPacker();
  packer
    .packInt(1)
    .packString("leo")
    .packArrayHeader(2)
    .packString("xxx-xxxx")
    .packString("yyy-yyyy");

byte[] msgpack = packer.toByteArray()

// Deserialize with MessageUnpacker
MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(msgpack);
int id = unpacker.unpackInt();             // 1
String name = unpacker.unpackString();     // "leo"
int numPhones = unpacker.unpackArrayHeader();  // 2
String[] phones = new String[numPhones];
for (int i = 0; i < numPhones; ++i) {
  phones[i] = unpacker.unpackString();   // phones = {"xxx-xxxx", "yyy-yyyy"}
}
unpacker.close();

See also here for more advanced usages.

Clone this wiki locally