Jackson Full Data Binding: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 40: Line 40:
Example:
Example:


<pre>
<syntaxhighlight lang='java'>
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper;


Line 49: Line 49:
mapper.writeValue(baos, root);
mapper.writeValue(baos, root);
System.out.println(new String(baos.toByteArray()));
System.out.println(new String(baos.toByteArray()));
</pre>
</syntaxhighlight>


=Code Example=
=Code Example=

Revision as of 00:35, 14 November 2018

Internal

Overview

JSON to Java

import com.fasterxml.jackson.databind.ObjectMapper;

InputStream is = ...;

ObjectMapper mapper = new ObjectMapper();

Root root = mapper.readValue(is, Root.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);
    }
}

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 mapper = new ObjectMapper();
Root root = ... // some hierarchical object
mapper.writeValue(baos, root);
System.out.println(new String(baos.toByteArray()));

Code Example

Full Data Binding Example

Generics Handling

To enable generic type information (like "Map<String,Object>"), you have to use TypeReference container. See http://wiki.fasterxml.com/JacksonDataBinding.

Full Data Binding and Generics Example

Annotations

Jackson Annotations

Abstract Class Handling

Abstract Class Handling

Custom Deserializers

Custom Deserializers