3

I have a requirement to connect to a third party system and retrieve some data, via TCP/socket. The data format that will be sent is in a fixed length format and in binary.

Example of a request:

short MessageID = 5;
int TransactionTrace = 1; 

Basically, the I must send 6 bytes to the third party system. Data in Hex: 000500000001

I have tried to do the following in Java, but it doesn't work.

  1. Create a class with two variables and the correct data types (messageID & transactionTrace)
  2. Serialize the class to a byte array

The serialization returns far too many bytes.

Can someone please assist?

Thank you.

Java Class:

public final class MsgHeader implements Serializable  {

    public short MessageID;
    public int TransactionTrace;
}

Serialization:

MsgHeader header = new MsgHeader(); 
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = null;

try 
{
      out = new ObjectOutputStream(bos);   
      out.writeObject(header);
      byte[] yourBytes = bos.toByteArray();     

      System.out.println("Hex Data : " + getHex(yourBytes));              
} 
1
  • Serialization doesn't work that way. If you had read the documentation you'd know. Commented Aug 18, 2015 at 12:42

1 Answer 1

4

Java serialization uses its own format which is very unlikely to match what you're after.

I'd create a separate marshaller class using ByteBuffer to write out the values in the correct format. This will also allow specification of big or little endian.

private static class Message {
    short messageID = 5;
    int transactionTrace = 1;
    public short getMessageID() {
        return messageID;
    }

    public int getTransactionTrace() {
        return transactionTrace;
    }
}

private static class MessageMarshaller {
    public static byte[] toBytes(Message message) {
        ByteBuffer buffer = ByteBuffer.allocate(6);
        buffer.order(ByteOrder.BIG_ENDIAN);
        buffer.putShort(message.getMessageID());
        buffer.putInt(message.getTransactionTrace());
        return buffer.array();
    }
}

public static void main(String[] args) {
    System.out.println(Arrays.toString(MessageMarshaller.toBytes(new Message()))); 
    // ==> Outputs [0, 5, 0, 0, 0, 1]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation and solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.