8

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]

Enrichman
  • 11,157
  • 11
  • 67
  • 101
  • Yep, that was exactly the class which I was referring to, "For internal use only.". (And moreover I don't have the spring-security in the classpath). Thanks for the link btw. – Enrichman Nov 16 '12 at 10:47

3 Answers3

20

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • 1
    In the end I've used the `DatatypeConverter.parseBase64Binary(String content);` and is working but I guess that would work too. : ) – Enrichman Nov 27 '12 at 08:53
8

For those using Java8, Base64 encoding/decoding is now fully supported and a third party library is no longer needed. Plus it's even simpler (reduced from three lines to two) and a little more straight forward.

byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);
DavidR
  • 6,622
  • 13
  • 56
  • 70
1

There is an utility class with one-line solution to base64 encoding/decoding problem in official Spring documentation.

byte[] bytes = Base64Utils.decodeFromString(b64String);
StalkAlex
  • 743
  • 7
  • 16