在本测试代码中,我们定义了一个 POJO 类,名字为 MessageData,你可以访问下面的链接找到有关这个类的定义。
https://github.com/cwiki-us-demo/serialize-deserialize-demo-java/blob/master/src/main/java/com/insight/demo/serialize/model/msgpack/MessageData.java
POJO 的序列化和反序列化
你仅仅需要对MessagePackFactory进行实例化,然后传递参数到com.fasterxml.jackson.databind.ObjectMapper的构造方法。
然后你就可以用与jackson-databind相同的方法使用MessagePack格式化数据。
本测试方法,可以在https://github.com/cwiki-us-demo/serialize-deserialize-demo-java/blob/master/src/test/java/com/insight/demo/serialize/MessagePackSerializer.java中找到。
/**
* SerializationPOJO
*/
@Test
public void testMessagePackSerializationPOJO() {
byte[] bytes = new byte[0];
String uuid = UUID.randomUUID().toString();
// Instantiate ObjectMapper for MessagePack
ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
MessageData pojo = new MessageData();
pojo.setUuid(uuid);
pojo.setName("CWIKI.US");
try {
// Serialize a Java object to byte array
bytes = objectMapper.writeValueAsBytes(pojo);
logger.debug("Length of Bytes: [{}]", bytes.length);
// Deserialize the byte array to a Java object
MessageData deserialized = objectMapper.readValue(bytes, MessageData.class);
logger.debug("Deserialized Name: [{}]", deserialized.name);
assertEquals("CWIKI.US", deserialized.name);
} catch (JsonProcessingException ex) {
logger.error("Serialize Error", ex);
} catch (IOException e) {
e.printStackTrace();
}
}
https://www.cwiki.us/display/Serialization/MessagePack+Jackson+Dataformat