user4146491
user4146491

Reputation:

Java - Object to Fixed Byte Array

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

Upvotes: 3

Views: 379

Answers (1)

Adam
Adam

Reputation: 36703

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]
}

Upvotes: 4

Related Questions