I have written a recursive code in order to achieve this,
Here is the code if anyone else has encountered this issue:
public byte[] convert(JSONObject data) throws IOException, JSONException {
MessageBufferPacker packer = MessagePack.newDefaultBufferPacker();
packJObject(packer, data);
packer.close();
return packer.toByteArray();
}
private void packJObject(MessageBufferPacker packer, JSONObject data) throws IOException, JSONException {
packer.packMapHeader(data.length());
Iterator<String> keys = data.keys();
while(keys.hasNext()) {
String key = keys.next();
packer.packString(key); // pack the key
Object value = data.get(key);
if(value instanceof JSONArray) {
packJArray(packer, (JSONArray)value);
}
else if(value instanceof JSONObject) {
packJObject(packer, (JSONObject) value);
}
else {
packPrimitive(packer, value);
}
}
}
private void packJArray(MessageBufferPacker packer, JSONArray data) throws IOException, JSONException {
packer.packArrayHeader(data.length());
for(int i = 0; i < data.length(); i++) {
Object value = data.get(i);
if(value instanceof JSONObject) {
packJObject(packer,(JSONObject)value);
}
else if(value instanceof JSONArray){
packJArray(packer,(JSONArray)value);
}
else {
packPrimitive(packer, value);
}
}
}
private void packPrimitive(MessageBufferPacker packer, Object value) throws IOException {
if(value instanceof String) {
packer.packString((String)value);
}
else if(value instanceof Integer) {
packer.packInt((Integer) value);
}
else if(value instanceof Boolean) {
packer.packBoolean((boolean)value);
}
else if(value instanceof Double) {
packer.packDouble((double)value);
}
else if(value instanceof Long) {
packer.packLong((long)value);
}
else {
throw new IOException("Invalid packing value of type " + value.getClass().getName());
}
}