javaarrayssalesforce

String to byte Array without encoding in Java


I am using com.google.protobuf.ByteString and trying to serialize it so I can store it as a string.

String value = Arrays.toString(byteString.toByteArray());

Now I want to reverse it and change it back into a byteString.

byte[] byteArray = value.getBytes(); ??
ByteString.copyFrom(byteArray);

I doubt this is going to work. An example of a ByteString in string format using the first line above looks like this [0, 0, 0, 0, 1, -118, 7, -52, 0, 0]. Which is fine, I don't mind storing this. It seems like these characters are represented entirely as numbers. Now I want to reverse it so I can recreate a ByteString. The problem is I do not know how to convert it back into a byte array and undo Arrays.toString(byte[]).

I do not know the encoding on the byte array originally. Its from saleforce replay id. I also do not have an easy way to store it as byte data. Is there some fancy Arrays.UndoString() or do I have to write my own function?


Solution

  • Arrays.toString isn't really meant to be undone. Sure you could write a parser for it. But why would you, if there are alternatives available?

    Alternative 1: Base64

    Use

    import java.util.Base64;
    Base64.getEncoder().encodeToString(yourarray)
    

    to convert your array into a string and

    Base64.getDecoder().decode(yourstring)
    

    to get the array back.

    Alternative 2: JSON

    Results in more readable Strings, but requires an external library of which there are many. Therefore I won't give any example code here.