Decode Base64 with Jackson (or Spring)

2019-05-04 07:40发布

问题:

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]

回答1:

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.



回答2:

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);


回答3:

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

byte[] bytes = Base64Utils.decodeFromString(b64String);