Decode Base64 with Jackson (or Spring)

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!