咱们在使用 MessagePack 对 List 对象数据进行序列化的时候,发现序列化之后的二进制数组数据偏大的状况。java
请注意,不是全部的 List 对象都会出现这种状况,这个根据你 List 对象中存储的内容有关。git
有关本问题的测试源代码请参考:https://github.com/cwiki-us-demo/serialize-deserialize-demo-java/blob/master/src/test/java/com/insight/demo/serialize/MessagePackDataTest.java 中的内容。github
考察下面的代码:数组
List<MessageData> dataList = MockDataUtils.getMessageDataList(600000); ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory()); raw = objectMapper.writeValueAsBytes(dataList); FileUtils.byteCountToDisplaySize(raw.length); logger.debug("Raw Size: [{}]", FileUtils.byteCountToDisplaySize(raw.length));
咱们会发现,针对这个 60 万个对象的 List 的序列化后的数据达到了 33MB。app
若是咱们再定义 ObjectMapper 对象的时候添加一部分参数,咱们会发现大小将会有显著改善。测试
请参考下面的代码:debug
List<MessageData> dataList = MockDataUtils.getMessageDataList(600000); ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory()); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.setAnnotationIntrospector(new JsonArrayFormat()); rawJsonArray = objectMapper.writeValueAsBytes(dataList); logger.debug("rawJsonArray Size: [{}]", FileUtils.byteCountToDisplaySize(rawJsonArray.length));
若是你运行上面的代码,你会看到程序的输出字符串将会下降到 23MB。code
这里面主要是 objectMapper.setAnnotationIntrospector(new JsonArrayFormat());
这句话起了做用。orm
在正常的场景中,咱们能够经过 注解 JsonIgnore, 将其加到属性上,即解析时即会过滤到属性。对象
而实际实现,则是由类 JacksonAnnotationIntrospector
中 的 hasIgnoreMarker
来完成,则就是经过读取注解来判断属性是否应该被exclude掉。ObjectMapper
中默认的 AnnotationIntrospector
便是 JacksonAnnotationIntrospector
来完成,但咱们能够经过 方法 ObjectMapper.setAnnotationIntrospector
来从新指定自定义的实现。
https://www.cwiki.us/display/Serialization/MessagePack+Jackson+Data+Size