Jackson Simple Data Binding: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 8: Line 8:


=JSON to Java=
=JSON to Java=
JSON to Java parsing is done by <tt>ObjectMapper.readValue()</tt>, which must be called with a type corresponding to the top-level JSON data type, usually a Map.
type and it will build a Map/List/String/Number/Boolean hierarchy:
<pre>
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper om = new ObjectMapper();
Map root = on.readValue(inputStream, Map.class);
</pre>
Most generically:
<pre>
Object root = mapper.readValue(src, Object.class);
</pre>
It is possible to enable generic type information (like <tt>Map<String, Object></tt>). For details, see [[Jackson Full Data Binding#generic_type_information|Full Data Binding]].


==JSON to Java Code Example==
==JSON to Java Code Example==

Revision as of 20:17, 26 February 2017

Internal

Overview

Simple data binding extracts data from JSON and initializes a in-memory Java object hierarchy. Unlike the tree model, which uses JsonNodes, simple data binding uses Maps, Lists, Strings, Numbers, Booleans and nulls to represent the JSON structure. 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 a type corresponding to the top-level JSON data type, usually a Map.


type and it will build a Map/List/String/Number/Boolean hierarchy:
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper om = new ObjectMapper();

Map root = on.readValue(inputStream, Map.class);

Most generically:

Object root = mapper.readValue(src, Object.class);

It is possible to enable generic type information (like Map<String, Object>). For details, see Full Data Binding.

JSON to Java Code Example

https://github.com/NovaOrdis/playground/blob/master/json/jackson/simple-data-binding-json-to-java/src/main/java/io/novaordis/playground/json/jackson/simpledatabinding/json2java/Main.java

Java to JSON

ObjectMapper om = new ObjectMapper();

Map root = ...

om.writeValue(baos, root);

Java to JSON Code Example