This is the first time that I try to handle binary data so I'm quite new to this. I'm writing a REST service for uploading stuff, and I'm going to receive a Base64 encoded String.
I've found this (standard Java), and I've also found an internal Spring class (bad idea).
Is there a Jackson annotation to automatically decode a property from Base64? Should I use String or byte[] in my Object?
I'm also using Spring MVC 3, so it will be ok to have a class from the Spring framework to do this.
[please, no Apache Commons. I would like to find a solution without adding more stuff]
To decode with base64 you need to use the --decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it. Using the example encoding shown above, let's decode it back into its original form. Provided your encoding was not corrupted the output should be your original string.
Base64 is an encoding, the strings you've posted are encoded. You can DECODE the base64 values into bytes (so just a sequence of bits). And from there, you need to know what these bytes represent and what original encoding they were represented in, if you wish to convert them again to a legible format.
The equals sign "=" represents a padding, usually seen at the end of a Base64 encoded sequence. The size in bytes is divisible by three (bits divisible by 24): All bits are encoded normally.
Instances of Base64. Decoder class are safe for use by multiple concurrent threads. Unless otherwise noted, passing a null argument to a method of this class will cause a NullPointerException to be thrown.
Use byte[]
for property, and Base64 encoding/decoding "just works". Nothing additional to do.
Additionally, Jackson can do explicit conversion by something like:
ObjectMapper mapper = new ObjectMapper();
byte[] encoded = mapper.convertValue("Some text", byte[].class);
String decoded = mapper.convertValue(encoded, String.class);
if you want to use Jackson for stand-alone Base64 encoding/decoding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With