Jackson Full Data Binding: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 34: Line 34:
<span id="generic_type_information"></span>To enable generic type information (like "Map<String,Object>"), you have to use TypeReference container as explained above.
<span id="generic_type_information"></span>To enable generic type information (like "Map<String,Object>"), you have to use TypeReference container as explained above.


==JSON to Java Code Example==
{{External|[https://github.com/NovaOrdis/playground/blob/master/json/jackson/full-data-binding-json-to-java/src/main/java/io/novaordis/playground/json/jackson/fulldatabinding/json2java/Main.java JSON to Java Full Data Binding Example]}}


=Java to JSON=
=Java to JSON=
Line 56: Line 53:
</pre>
</pre>


=Code Example=


==Java to JSON Code Example==
{{External|[https://github.com/NovaOrdis/playground/blob/master/json/jackson/full-data-binding/src/main/java/io/novaordis/playground/json/jackson/fulldatabinding/Main.java Full Data Binding Example]}}

Revision as of 21:45, 26 February 2017

Internal

Overview

JSON to Java

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper om = new ObjectMapper();
Token token = on.readValue(inputStream, Token.class);

This is a generic conversion method, assuming that the JSON content matches the internal structure of the type <T>:

public static <T> T fromJson(String json, Class<? extends T> c) throws JsonConversionException {

    try {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(new ByteArrayInputStream(json.getBytes()), c);
    }
    catch (Exception e) {
       throw new JsonConversionException(e);
    }
}


To enable generic type information (like "Map<String,Object>"), you have to use TypeReference container as explained above.


Java to JSON

ObjectMapper will introspect a Java object coded according to the Java Beans conventions and output it as JSON content.

The method names (without the "get") will be used as field names.

Example:

import com.fasterxml.jackson.databind.ObjectMapper;

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectMapper om = new ObjectMapper();
Object root = ... // some hierarchical object
om.writeValue(baos, root);
System.out.println(new String(baos.toByteArray()));

Code Example

Full Data Binding Example