Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending a byte array in json using jackson

Tags:

json

jackson

I want to form a JSON with two fields mimetype and value.The value field should take byte array as its value.

{    "mimetype":"text/plain",    "value":"dasdsaAssadsadasd212sadasd"//this value is of type byte[]  } 

How can I accomplish this task?

As of now I am using toString() method to convert the byte array into String and form the JSON.

like image 874
Sudhagar Sachin Avatar asked Jul 18 '12 17:07

Sudhagar Sachin


People also ask

Can I send byte array in JSON?

JSON does not support that. Use Base64. That is your library supporting it, not JSON itself. The byte array wont be stored as byte array in the JSON, JSON is a text format meant to be human readable.

How does Jackson convert object to JSON?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.

How do you deserialize byte array?

Here is the code in reverse to deserialize: var set = new DataSet(); try { var content = StringToBytes(s); var formatter = new BinaryFormatter(); using (var ms = new MemoryStream(content)) { using (var ds = new DeflateStream(ms, CompressionMode. Decompress, true)) { set = (DataSet)formatter.

How does Jackson parse JSON?

databind. ObjectMapper ) is the simplest way to parse JSON with Jackson. The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON.


2 Answers

If you are using Jackson for JSON parsing, it can automatically convert byte[] to/from Base64 encoded Strings via data-binding.

Or, if you want low-level access, both JsonParser and JsonGenerator have binary access methods (writeBinary, readBinary) to do the same at level of JSON token stream.

For automatic approach, consider POJO like:

public class Message {   public String mimetype;   public byte[] value; } 

and to create JSON, you could do:

Message msg = ...; String jsonStr = new ObjectMapper().writeValueAsString(msg); 

or, more commonly would write it out with:

OutputStream out = ...; new ObjectMapper().writeValue(out, msg); 
like image 171
StaxMan Avatar answered Sep 19 '22 23:09

StaxMan


You can write your own CustomSerializer like this one:

public class ByteArraySerializer extends JsonSerializer<byte[]> {  @Override public void serialize(byte[] bytes, JsonGenerator jgen,         SerializerProvider provider) throws IOException,         JsonProcessingException {     jgen.writeStartArray();      for (byte b : bytes) {         jgen.writeNumber(unsignedToBytes(b));     }      jgen.writeEndArray();  }  private static int unsignedToBytes(byte b) {     return b & 0xFF;   }  } 

This one returns an unsigned byte array representation instead of a Base64 string.

How to use it with your POJO:

public class YourPojo {      @JsonProperty("mimetype")     private String mimetype;     @JsonProperty("value")     private byte[] value;        public String getMimetype() { return this.mimetype; }     public void setMimetype(String mimetype) { this.mimetype = mimetype; }      @JsonSerialize(using= com.example.yourapp.ByteArraySerializer.class)     public byte[] getValue() { return this.value; }     public void setValue(String value) { this.value = value; }   } 

And here is an example of it's output:

{     "mimetype": "text/plain",     "value": [         81,         109,         70,         122,         90,         83,         65,         50,         78,         67,         66,         84,         100,         72,         74,         108,         89,         87,         48,         61     ] } 

P.S.: This serializer is a mix of some answers that I found on StackOverflow.

like image 28
Alberto Estrella Avatar answered Sep 20 '22 23:09

Alberto Estrella