2

I have a JsonObject that contains several JsonArrays:

{
    "key1" : [[1, 2, 3, 4]],
    "key2" : [[1, 2, 3, 4]]
}

I would like to pack it using MessagePack without using the JsonObjects string representation,

So far i haven't found any documentation as to how to accomplish this,

Any ideas?

1 Answers1

1

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());
    }
}