Saturday, 14 September 2013

How to use Messagepack with JSON?

How to use Messagepack with JSON?

I am planning to use Messagepack in our project. Currently, we are using
JSON in our project and we are writing serialize JSON document into
Cassandra. Now we are thinking to use Messagepack which is an efficient
binary serialization format.
And I believe using MessagePack in our project is almost a drop-in
optimization. Below is my code which is serializing the JSON document
using ObjectMapper.
public static void main(String[] args) throws IOException {
final long lmd = System.currentTimeMillis();
Map<String, Object> props = new HashMap<String, Object>();
props.put("site-id", 0);
props.put("price-score", 0.5);
props.put("confidence-score", 0.2);
Map<String, Category> categories = new HashMap<String, Category>();
categories.put("123", new Category("0.4", "0.2"));
categories.put("321", new Category("0.2", "0.5"));
props.put("categories", categories);
AttributeValue av = new AttributeValue(); // using Jackson in this class
av.setProperties(props);
Attribute attr = new Attribute(); // using jackson in this class
attr.instantiateNewListValue();
attr.getListValue().add(av);
attr.setLastModifiedDate(lmd);
System.out.println(attr);
// serialize it
try {
String jsonStr = new ObjectMapper().writeValueAsString(attr);
// write into database
System.out.println(jsonStr);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Both of my classes, AttributeValue and Attribute are using Jackson
annotations and making a JSON document for me.
Now I am not sure, how to use Messagepack in my above code as I am not
able to find clear documentation on it. Can anyone help me with that?

No comments:

Post a Comment