Jackson Simple Data Binding: Difference between revisions
Line 50: | Line 50: | ||
It is possible to call readValue() with a more specific type. For example, if the top level JSON value is an Object, readValue() can be called upon a Map. | It is possible to call readValue() with a more specific type. For example, if the top level JSON value is an Object, readValue() can be called upon a Map. | ||
< | <syntaxhighlight lang='java'> | ||
import com.fasterxml.jackson.databind.ObjectMapper; | import com.fasterxml.jackson.databind.ObjectMapper; | ||
Line 56: | Line 56: | ||
Map root = mapper.readValue(inputStream, Map.class); | Map root = mapper.readValue(inputStream, Map.class); | ||
</ | </syntaxhighlight> | ||
However, if the top level JSON value is a List, the code above will throw an exception: | However, if the top level JSON value is a List, the code above will throw an exception: |
Revision as of 00:32, 14 November 2018
Internal
Overview
Simple data binding extracts data from JSON and initializes an in-memory Java object hierarchy. Unlike the tree model, which uses JsonNodes, simple data binding assembles the hierarchy representing the JSON data out of Maps, Lists, Strings, Numbers, Booleans and nulls. A Map/List/String/Number/Boolean hierarchy can be written out as JSON content.
JSON to Java
JSON to Java parsing is done by ObjectMapper.readValue(), which must be called with an Object.class type:
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
Object root = mapper.readValue(src, Object.class);
if (root instance of Map) {
...
}
else if (root instanceof List) {
...
}
...
This is the conversion table:
JSON Type | Java Type |
object | LinkedHashMap<String,Object> |
array | ArrayList<Object> |
string | String |
number (no fraction) | Integer, Long or BigInteger (smallest applicable) |
number (fraction) | Double (configurable to use BigDecimal) |
false | Boolean |
null | null |
It is possible to call readValue() with a more specific type. For example, if the top level JSON value is an Object, readValue() can be called upon a Map.
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
Map root = mapper.readValue(inputStream, Map.class);
However, if the top level JSON value is a List, the code above will throw an exception:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token
JSON to Java Code Example
Generics Support
It is possible to enable generic type information (like Map<String, Object>). For details, see Full Data Binding.
Java to JSON
The Map/List/String/Number/Boolean hierarchy can be written out as JSON by ObjectMapper.writeValue().
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectMapper om = new ObjectMapper(); Map root = ... om.writeValue(baos, root); System.out.println(new String(baos.toByteArray()));