Search code examples
javac#serializationmemorystreambinaryformatter

Deserialize RabbitMQ message generated by C# in Java


I have a RabbitMQ data service in C# and "fout" some messages. The subscripber/client is in Java. I can receive message, I know how to deserialize in C#, but I do not know how to deserialize the message to object. in Java.

C# Serialize:

byte[] message;
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
    bf.Serialize(ms, updateMessage);
    message = ms.ToArray();
}

C# Deserialize:

MyObject message = null;
using (var memStream = new MemoryStream())
{
    var binForm = new BinaryFormatter();
    memStream.Write(body, 0, body.Length);
    memStream.Seek(0, SeekOrigin.Begin);
    message = (MyObject)binForm.Deserialize(memStream);
}

Java Receiver:

@RabbitListener(queues = queueName)
public void receive(??? message ) {
    // deserailize message right here
    // btw, I do not know what type of received message should be initialized.
}

Solution

  • Deserializing an object in Java that was serialized with .NET's build in binary serializer is not possible without great difficulty (you would have to implement the deserializer yourself).

    The easiest option would be to use a text-based serialization option such as JSON and XML. There are plenty of tutorials on how to-do this in both C# and Java.

    If you need to use a binary format some options to look into would be Google's protocol buffers or apache thrift.