Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson Custom Mapper to convert Byte Array to String

I'm incredibly new to Jackson and I have a problem with understanding how I could accomplish something.

I've got some data that is of type byte[] (the data is within classes generated from JAXB). Before the data is sent to the browser, Jackson then (I believe) turns it into JSON so that the webpage can consume it. At least that is my crude understanding, so far.

The JSON data shows my byte [] as strings, which don't match the display that we want. For instance, the actual data might be CAFEDEAD but the JSON string looks like 3q2+78r+. I'd like the JSON to contain the string CAFEDEAD

My question is, can I write something custom for Jackson that before it creates the final JSON, turn the byte[] data into a readable hex string? Or if not, what other options do I have?

I have access to the javascript so if there is a way to turn the JSON string back, i'm up for that as well.

like image 544
Robb Avatar asked Nov 04 '22 01:11

Robb


1 Answers

Jackson will convert byte[] into Base64-encoded binary data. This is the safe way to pass binary content. Otherwise there is no way to know which character encoding might be used by contained data, so trying to build a String out of it would be risky and error-prone.

So the simplest way would be to have receiver base64 decode contents back into binary data.

You could alternatively add custom serializer to turn into other representations (hex, base85), but it really depends on what the goal is.

like image 187
StaxMan Avatar answered Nov 09 '22 12:11

StaxMan