How to Convert Object to Byte Array in Java using Jackson

Published Jun 1, 2022

How can we serialize an object into a byte array using Jackson?

Suppose we have a static ObjectMapper available.

public static final ObjectMapper OBJECT_MAPPER;

Using writeValueAsBytes(), we can serialize any Java object as a byte array.

public static <T> byte[] convertToJsonBytes(T obj) {
  try {
    return OBJECT_MAPPER.writeValueAsBytes(obj);
  } catch (JsonProcessingException e1) {
    throw new RuntimeException(e1);
  }
}

Prior to version 2.1, this method could throw an IOException.

In version 2.1, we can just handle JsonProcessingException, which will throw a standard RunTimeException.