Skip to main content

MessagePack Serializers

The MsgPackSerializer class is used to serialize POJOs into MessagePack.

When to use it​

Use MsgPackSerializer when you want JSON's data model in a compact binary form: smaller than JSON on the wire and faster to parse, at the cost of not being human readable. It writes byte[], so use it for binary protocols, message queues and caches rather than for browsers.

Example​

import org.apache.juneau.marshall.msgpack.*;

public class MsgPackSerializerExample {

public static class Person {
public String name = "John Smith";
public int age = 45;
}

public static void main(String[] args) throws Exception {
Person person = new Person();

// Binary output.
byte[] bytes = (byte[]) MsgPackSerializer.DEFAULT.write(person);

// The same bytes as spaced hex, for reading.
System.out.println(bytes.length + " bytes");
System.out.println(MsgPackSerializer.DEFAULT_SPACED_HEX.writeToString(person));
}
}

The bean is 22 bytes; the same data as JSON is 30 characters.

Options​

The following pre-configured serializers are provided for convenience:

InstanceOutput
MsgPackSerializer.DEFAULTBinary byte[].
MsgPackSerializer.DEFAULT_SPACED_HEXThe same bytes as a hex string.
MsgPackSerializer.DEFAULT_BASE64The same bytes as a Base64 string.

For anything else, start from the builder's create() method. The settings readers reach for first:

Builder methodEffect
addBeanTypesMsgPack()Add _type properties to beans whose runtime type differs from the declared one.
keepNullProperties()Write bean properties whose value is null.
trimEmptyCollections() / trimEmptyMaps()Skip empty collections or maps.
sortCollections() / sortMaps()Sort collections or map entries before writing.
beanDictionary(Class...)Classes whose _type names the serializer may write.
swaps(Class...)Object swaps that convert values before writing.

The class hierarchy for the builder of this serializer is below. Refer to the builder javadocs for the full set of configurable settings.

Context.BuilderMarshallingContextable.BuilderMarshallingTraverseContext.BuilderSerializer.BuilderOutputStreamSerializer.BuilderMsgPackSerializer.Builder

See also​