在本測試代碼中,咱們定義了一個 POJO 類,名字爲 MessageData,你能夠訪問下面的連接找到有關這個類的定義。java
你僅僅須要對 MessagePackFactory
進行實例化,而後傳遞參數到 com.fasterxml.jackson.databind.ObjectMapper
的構造方法。github
而後你就能夠用與 jackson-databind
相同的方法使用 MessagePack
格式化數據。app
本測試方法,能夠在 https://github.com/cwiki-us-demo/serialize-deserialize-demo-java/blob/master/src/test/java/com/insight/demo/serialize/MessagePackSerializer.java 中找到。dom
/** * 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測試