Skip to content

Instantly share code, notes, and snippets.

@muga
Created September 15, 2013 09:07
Show Gist options
  • Save muga/6569065 to your computer and use it in GitHub Desktop.
Save muga/6569065 to your computer and use it in GitHub Desktop.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.msgpack.MessagePack;
import org.msgpack.packer.Packer;
import org.msgpack.type.MapValue;
import org.msgpack.type.Value;
import org.msgpack.type.ValueType;
import org.msgpack.unpacker.Unpacker;
public class SerDe {
private MessagePack msgpack = new MessagePack();
public byte[] serializeMapGenericMap(User.Value v) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Packer packer = msgpack.createPacker(out);
packer.write(v.getProperties());
packer.close();
return out.toByteArray();
}
public User.Value deserializeGenericMap(byte[] b) throws IOException {
Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(b));
MapValue mapValue = unpacker.readValue().asMapValue();
Map<String, Object> map = new HashMap<String, Object>();
for (Map.Entry<Value, Value> e : mapValue.entrySet()) {
String key = e.getKey().asRawValue().getString();
Object val = deserializeObject(e.getValue());
map.put(key, val);
}
User.Value v = new User.Value();
v.setProperties(map);
return v;
}
private Object deserializeObject(Value v) {
ValueType t = v.getType();
if (t == ValueType.NIL) {
return null;
} else if (t == ValueType.BOOLEAN) { // boolean
return v.asBooleanValue().getBoolean();
} else if (t == ValueType.INTEGER) { // integer, long, ...
return v.asIntegerValue().getLong();
} else if (t == ValueType.FLOAT) { // float, double, ..
return v.asFloatValue().getFloat();
} else if (t == ValueType.ARRAY) { // array
throw new UnsupportedOperationException("boolean");
} else if (t == ValueType.MAP) { // map
throw new UnsupportedOperationException("boolean");
} else if (t == ValueType.RAW) { // string
return v.asRawValue().getString();
} else {
throw new RuntimeException("fatal error");
}
}
public static void main(String[] args) throws Exception {
Map<String, Object> src = new HashMap<String, Object>();
src.put("k1", "v1");
src.put("k2", 2);
System.out.println("src: " + src);
User.Value srcValue = new User.Value();
srcValue.setProperties(src);
SerDe sd = new SerDe();
byte[] bytes = sd.serializeMapGenericMap(srcValue);
User.Value dstValue = sd.deserializeGenericMap(bytes);
System.out.println("dst: " + dstValue.getProperties());
}
}
class User {
public static class Value {
public Map<String, Object> properties; // change 'public' modifier
public Value() {
properties = new HashMap<String, Object>();
}
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> v) {
properties = v;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment