-
Notifications
You must be signed in to change notification settings - Fork 1
Chapter Intro ConvertValue
Aside from the core tasks of reading and writing JSON, Jackson also allows simple conversion of "structurally compatible" Java Objects.
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); };
A somewhat more interesting case is that of converting between POJOs and Map
s, like so:
User input = ...;
Map<String,Object> map = mapper.convertValue(input, Map.class);
// and back
User output = mapper.convertValue(map, User.class);
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);
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: Number
s can be converted into String
s (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.