How to Convert Object to JSON String in Java using Jackson


How can we serialize an object into a JSON string using Jackson?

Suppose we have a static ObjectMapper available.

public static final ObjectMapper OBJECT_MAPPER;

Using writeValueAsString(), we can serialize any Java object as a String.

public static <T> String convertToJson(T obj) {
  try {
    return OBJECT_MAPPER.writeValueAsString(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.