Skip to content

Chapter Intro ConvertValue

Tatu Saloranta edited this page Sep 7, 2016 · 2 revisions

Jackson Manual: Introduction - Convert Values

Aside from the core tasks of reading and writing JSON, Jackson also allows simple conversion of "structurally compatible" Java Objects.

Collections/arrays to Collections/arrays

As a simple example, you can convert from a simple List<String> into String[] very easily:

ObjectMapper mapper = ...;
List<String> input = new ArrayList<>();
input.add("first");
input.add("second");
String[] asArray = mapper.convertValue(input, String[].class);
// same as:
// String[] asArray = new String[] { input.get(0), input.get(1); };

POJOs to/from Maps

A somewhat more interesting case is that of converting between POJOs and Maps, like so:

User input = ...;
Map<String,Object> map = mapper.convertValue(input, Map.class);
// and back
User output = mapper.convertValue(map, User.class);

Base64 encoding/decoding

And yet more interesting is the case of Base64 encoding:

byte[] binary = ...;
String base64Encoded = mapper.convertValue(binary, String.class);

and decoding

byte[] result = mapper.convertValue(base64Encoded, byte[].class);

How does it work?

Conceptually you can think of conversion as a simplified "write as JSON, read back as result type" operation:

Object inputValue = ...;
Class<T> targetType = ....;

String json = mapper.writeValueAsString(inputValue);
T result = mapper.readValue(json, targetType);

which leads to the "structurally compatible" definition: two types are Structurally compatible if they produce the same or compatible JSON Structure. In simple case of List and Java array, JSON serializations would be identical, so conversion works without problems. But the "compatible" part means that all kinds of type coercions that are possible between POJOs and JSON are also allowed: Numbers can be converted into Strings (for example), and in certain cases single-element arrays may be coerced into non-array value.

In practice Jackson optimizes value conversions significantly so that there is no actual JSON generation at all; values and structure are kept in memory. But the observed behavior should be very close to that of actual write-as-JSON, read-from-JSON sequence.