Tech and Media Labs
This site uses cookies to improve the user experience.




Jackson - ObjectMapper

Jakob Jenkov
Last update: 2015-11-04

The simplest way to parse JSON with Jackson is via the Jackson databind ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper). Jackson's ObjectMapper can parse a JSON from a string, stream or file, and create an object graph representing the parsed JSON.

The classes used in the object graph can either be classed developed by you, or the built-in JSON tree model explained later in this tutorial.

Jackson Databind

The ObjectMapper is located in the Jackson Databind project, so your application will need that project on its classpath to work. See the Jackson Installation tutorial for more information.

Jackson ObjectMapper Example

Here is a quick Java Jackson ObjectMapper example:

ObjectMapper objectMapper = new ObjectMapper();


String carJson =
    "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";


try {

    Car car = objectMapper.readValue(carJson, Car.class);

    System.out.println("car.brand = " + car.brand);
    System.out.println("car.doors = " + car.doors);
} catch (IOException e) {
    e.printStackTrace();
}

The Car class was made by me. As you can see, the Car.class is parsed as the second parameter to the readValue() method. The first parameter of readValue() is the source of the JSON (string, stream or file).

Jackson Annotations

Jackson contains a set of Java annotations which you can use to modify how Jackson reads and writes JSON to and from Java objects. Jackson's annotations are explained in my Jackson annotation tutorial.

Jackson JSON Tree Model

Jackson has a built-in tree model which can be used to represent a JSON object. Jackson's tree model is useful if you don't know how the JSON you will receive looks, or if you for some reason cannot (or just don't want to) create a class to represent it.

The Jackson tree model is represented by the JsonNode class. You use the Jackson ObjectMapper to parse JSON into a JsonNode tree model, just like you would have done with your own class.

Jackson Tree Model Example

Here is a simple Jackson tree model example:

String carJson =
        "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";

ObjectMapper objectMapper = new ObjectMapper();

try {

    JsonNode node = objectMapper.readValue(carJson, JsonNode.class);

} catch (IOException e) {
    e.printStackTrace();
}

As you can see, the JSON string is parsed into a JsonNode object instead of a Car object, simply by passing the JsonNode.class as second parameter to the readValue() method instead of the Car.class used in the example earlier in this tutorial.

The Jackson JsonNode Class

Once you have parsed your JSON into a JsonNode (or a tree of JsonNode instances) you can navigate the JsonNode tree model. Here is a JsonNode example that shows how to access JSON fields, arrays and nested objects:

String carJson =
        "{ \"brand\" : \"Mercedes\", \"doors\" : 5," +
        "  \"owners\" : [\"John\", \"Jack\", \"Jill\"]," +
        "  \"nestedObject\" : { \"field\" : \"value\" } }";

ObjectMapper objectMapper = new ObjectMapper();


try {

    JsonNode node = objectMapper.readValue(carJson, JsonNode.class);

    JsonNode brandNode = node.get("brand");
    String brand = brandNode.asText();
    System.out.println("brand = " + brand);

    JsonNode doorsNode = node.get("doors");
    int doors = doorsNode.asInt();
    System.out.println("doors = " + doors);

    JsonNode array = node.get("owners");
    JsonNode jsonNode = array.get(0);
    String john = jsonNode.asText();
    System.out.println("john  = " + john);

    JsonNode child = node.get("nestedObject");
    JsonNode childField = child.get("field");
    String field = childField.asText();
    System.out.println("field = " + field);

} catch (IOException e) {
    e.printStackTrace();
}

Notice that the JSON string now contains an array field called owners and a nested object field called nestedObject.

Regardless of whether you are accessing a field, array or nested object you use the get() method of the JsonNode class. By providing a string as parameter to the get() method you can access a field of a JsonNode. If the JsonNode represents an array, you need to pass an index to the get() method instead. The index specifies what element in the array you want to get.

Reading JSON From a String

Reading JSON from a string is pretty easy. You have actually already seen an example of how. The JSON string is passed as the first parameter to the ObjectMapper's readValue() method. Here is another simplified example:

ObjectMapper objectMapper = new ObjectMapper();

String carJson =
    "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";

Car car = objectMapper.readValue(carJson, Car.class);

Reading JSON From a Reader

You can also read JSON from a Reader instance. Here is an example of how to do that:

ObjectMapper objectMapper = new ObjectMapper();

String carJson =
        "{ \"brand\" : \"Mercedes\", \"doors\" : 4 }";
Reader reader = new StringReader(carJson);

Car car = objectMapper.readValue(reader, Car.class);

Reading JSON From a File

Reading JSON from a file can of course be done via a FileReader (instead of a StringReader - see previous section), but also with a File object. Here is an example of reading JSON from a file:

ObjectMapper objectMapper = new ObjectMapper();

File file = new File("data/car.json");

Car car = objectMapper.readValue(file, Car.class);

Reading JSON From a URL

Reading JSON from a URL (java.net.URL)

ObjectMapper objectMapper = new ObjectMapper();

URL url = new URL("file:data/car.json");

Car car = objectMapper.readValue(url, Car.class);

This example uses a file URL, but you can use an HTTP URL too (similar to http://jenkov.com/some-data.json ).

Reading JSON From an InputStream

It is also possible to read JSON from an InputStream with the Jackson ObjectMapper. Here is an example of reading JSON from an InputStream :

ObjectMapper objectMapper = new ObjectMapper();

InputStream input = new FileInputStream("data/car.json");

Car car = objectMapper.readValue(input, Car.class);

Reading JSON From a Byte Array

Jackson also supports reading JSON from a byte array. Here is an example of reading JSON from a byte array:

ObjectMapper objectMapper = new ObjectMapper();

String carJson =
        "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";

byte[] bytes = carJson.getBytes("UTF-8");

Car car = objectMapper.readValue(bytes, Car.class);

Generate JSON From Objects

The Jackson ObjectMapper can also be used to generate JSON from an object. You do so using the one of the methods:

  • writeValue()
  • writeValueAsString()
  • writeValueAsBytes()

Here is an example of generating JSON from a Car object, like the ones used in earlier examples:

ObjectMapper objectMapper = new ObjectMapper();

Car car = new Car();
car.brand = "BMW";
car.doors = 4;

objectMapper.writeValue(
    new FileOutputStream("data/output-2.json"), car);

This example first creates an ObjectMapper, then a Car instance, and finally calls the ObjectMapper's writeValue() method which converts the Car object to JSON and writes it to the given FileOutputStream.

The ObjectMapper's writeValueAsString() and writeValueAsBytes() both generate JSON from an object, and return the generated JSON as a String or as a byte array. Here is an example showing how to call writeValueAsString():

ObjectMapper objectMapper = new ObjectMapper();

Car car = new Car();
car.brand = "BMW";
car.doors = 4;

String json = objectMapper.writeValueAsString(car);
System.out.println(json);

The JSON output from this example would be:

{"brand":"BMW","doors":4}

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC