35

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.

3 Answers 3

48

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);
Sign up to request clarification or add additional context in comments.

3 Comments

is there any documentation on this and is this functionality still the same? i am sending a byte array from spring boot rest controller. so does that mean it will automatically get converted to a base 64 string via jackson?
That would depend on Spring Boot: if it uses Jackson for sending/receiving POJO with byte[] field, yes. Some other kind of data uses different converters (for example query parameters).
The thing to know with readBinaryValue is that it expects the binary to be base 64 encoded, (standard JSON). However in the wil it's possible to see non standard JSON document that may contain binary data.
20

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.

1 Comment

Thanks, this worked for me. Also, I did some changes in ByteArraySerializer serialize() method. I need string representation of byte array. String str = new String(bytes); jgen.writeString(str);
3

You might want to use Base64 which converts binary data to a string. Most programming languages have implementations of base64 encoding and decoding. If you want to decode/encode in a browser, see this question.

1 Comment

But please be aware that there are various kinds of Base64.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.