Belgacem
Belgacem

Reputation: 193

How to convert binary payload (file) to byte[] in java?

I receive json data that contains binary data like that ,and I would like to convert that data to byte[] in java but I don't know how ?.

"payload": "7V1bcxs3ln6frfdcfvfbghfdX8HSw9Zu1QzzartyhblfdcvberCObjvJpkiJUpmhRI1pKXYeXHRsZLSrCy
5dElN5tfvQaO72TdSoiOS3TH8Yxdffgtg754679513qdfrgvlslsqdeqaepdccngrdzedrtghBD+d++e7v//p80/v96v7h+u72
+z1gfK/39x/+9t391cPTzeP88aE/++Fvvd53n+8+Xd1c/fBm/unqAf+7
N7v65en++vGP3vx2fvPHw/XDdwfpHf5mevhq/vQDcnAAwD+gEPwDF+bDxTv+3UF61d/4eesrfP356uFx"

Upvotes: 4

Views: 1337

Answers (3)

Stephen C
Stephen C

Reputation: 718768

Based on the observation that the "binary" string consists of ASCII letters, digits and "+" and "/", I am fairly confident that it is actually Base64 encoded data.

To decode Base64 to a byte[] you can do something like this:

String s = "7V1bcxs3ln6...";
byte [] bytes = java.util.Base64.getDecoder().decode(s);

The decode call will throw IllegalArgumentException if the input string is not properly Base64 encoded.


When I decoded that particular string using an online Base64 decoder, the result is unintelligible. But that is what I would expect for an arbitrary "blob" of binary data.

Upvotes: 5

Luis Estrada
Luis Estrada

Reputation: 449

In my case I had to convert payload that I knew it was a text something like:

{"payload":"eyJ1c2VyX2lkIjo0LCJ1c2VybmFtZSI6IngiLCJjaXR5IjoiaGVyZSJ9"}

This is the difference between java.util.Base64.getDecoder() and getBytes():

    String s = "eyJ1c2VyX2lkIjo0LCJ1c2VybmFtZSI6IngiLCJjaXR5IjoiaGVyZSJ9";
    byte [] bytes = s.getBytes();
    byte [] bytes_base64 = java.util.Base64.getDecoder().decode(s);
    String bytesToStr = new String(bytes, StandardCharsets.UTF_8);
    String bytesBase64Tostr = new String(bytes_base64, StandardCharsets.UTF_8);
    
    System.out.println("bytesToStr="+bytesToStr);
    System.out.println("bytesBase64Tostr="+bytesBase64Tostr);

Output:

bytesToStr=eyJ1c2VyX2lkIjo0LCJ1c2VybmFtZSI6IngiLCJjaXR5IjoiaGVyZSJ9

bytesBase64Tostr={"user_id":4,"username":"x","city":"here"}

java.util.Base64.getDecoder() worked for in my case

Upvotes: 0

Mark Bramnik
Mark Bramnik

Reputation: 42441

In general if you have a String in some object that denotes the json payload you can :

String s = "7V1bcxs3ln6...";
byte [] bytes = s.getBytes();

Other than that if this payload should be decoded somehow then additional code will be required.

Upvotes: 2

Related Questions