4

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"
1
  • Looks like base64. Commented May 7, 2020 at 7:12

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.