MessagePack Java Jackson Dataformat – Map 的序列化和反序列化

本测试方法,可以在 https://github.com/cwiki-us-demo/serialize-deserialize-demo-java/blob/master/src/test/java/com/insight/demo/serialize/MessagePackSerializer.java 中找到。

我们需要定义测试需要的 MAP,定义 Map 的方法你可以在下面的测试程序中找到。

/**
  * SerializationMap
  */
 @Test
 public void testMessagePackSerializationMap() {

     byte[] bytes = new byte[0];
     String uuid_a = UUID.randomUUID().toString();
     String uuid_b = UUID.randomUUID().toString();

     // Instantiate ObjectMapper for MessagePack
     ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());

     Map<String, MessageData> map = new HashMap<>();
     MessageData messageData = new MessageData();

     // Element A in MAP
     messageData.setUuid(UUID.randomUUID().toString());
     messageData.setName("CWIKI.US - A");
     map.put(uuid_a, messageData);

     // Element B in MAP
     messageData = new MessageData();
     messageData.setUuid(UUID.randomUUID().toString());
     messageData.setName("CWIKI.US - B");
     map.put(uuid_b, messageData);


     try {
         // Serialize a Java object to byte array
         bytes = objectMapper.writeValueAsBytes(map);
         logger.debug("Length of Bytes: [{}]", bytes.length);

         // Deserialize the byte array to a MAP
         Map<String, MessageData> deserialized = objectMapper.readValue(bytes, new TypeReference<Map<String, MessageData>>() {
         });
         logger.debug("Deserialized MAP Count: [{}]", deserialized.size());
         logger.debug("MAP index 0: [{}]", deserialized.get(uuid_a).getName());

         assertEquals("CWIKI.US - A", deserialized.get(uuid_a).getName());

     } catch (JsonProcessingException ex) {
         logger.error("Serialize Error", ex);
     } catch (IOException e) {
         e.printStackTrace();
     }


 }

https://www.cwiki.us/display/Serialization/MessagePack+Jackson+Dataformat

 

您可以在保留原文链接的情况下转载:HoneyMoose » MessagePack Java Jackson Dataformat – Map 的序列化和反序列化

赞 (0) 打赏

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏