Boon - ObjectMapper

Jakob Jenkov
Last update: 2015-07-01

Once you have installed Boon you can start parsing JSON into objects using the Boon ObjectMapper class.

The Boon ObjectMapper class is designed to have an interface similar to both GSON and the Jackson ObjectMapper classes. This makes it easier to switch to Boon from GSON or Jackson.

Creating an ObjectMapper

Before you can use the Boon ObjectMapper you must first create an instance of it. You do so via the JsonFactory's static create() method. Here is an example of how you create a Boon ObjectMapper in Java code:

ObjectMapper mapper = JsonFactory.create();

Parsing JSON Into Objects

The Boon ObjectMapper can parse JSON into object graphs. Here is an example of parsing JSON into an object graph with the Boon ObjectMapper:

String fleetStr = "{" +
        "  \"cars\" : [" +
        "     { \"brand\" : \"Audi\", \"doors\" : 4 }" +
        "    ,{ \"brand\" : \"Mercedes\", \"doors\" : 3}" +
        "    ,{ \"brand\" : \"BMW\",  \"doors\" : 2 }" +
        "  ]" +
        "}";

ObjectMapper mapper = JsonFactory.create();

Fleet fleet = mapper.readValue(fleetStr, Fleet.class);

The Fleet and Car classes look like this:

public class Fleet {
    public Car[] cars = null;
}
public class Car {

    public String brand = null;
    public int    doors = 0;

    public Car() {}

    public Car(String brand, int doors) {
        this.brand = brand;
        this.doors = doors;
    }
}

Notice that the example called the readValue() method of the ObjectMapper class. This method's name and parameters are similar to those of Jackson's ObjectMapper.

Boon also has a fromJson() method which does the same as the readValue() method, but looks more like the GSON interface. Here is the same example using the fromJson() method:

String fleetStr = "{" +
        "  \"cars\" : [" +
        "     { \"brand\" : \"Audi\", \"doors\" : 4 }" +
        "    ,{ \"brand\" : \"Mercedes\", \"doors\" : 3}" +
        "    ,{ \"brand\" : \"BMW\",  \"doors\" : 2 }" +
        "  ]" +
        "}";

ObjectMapper mapper = JsonFactory.create();

Fleet fleet = mapper.fromJson(fleetStr, Fleet.class);

If you come from using Jackson or GSON, switching to Boon will thus be easier, as Boon contains methods that work similarly to the methods you were used to from GSON or Jackson. Just remember, they are similar, but not exactly the same. There are slight differences in exceptions thrown, parameters etc. You will quickly overcome those minor differences though.

Parsing JSON into Maps

Sometimes it is easier to parse a JSON object into a Map than to create a custom class to hold the parsed JSON. Boon can do this very easily. All you have to do is to pass Map.class as second parameter to the readValue() ( or fromJson() ) method. Here is an example of parsing JSON into a Map with Boon:

String fleetStr = "{" +
        "  \"cars\" : [" +
        "     { \"brand\" : \"Audi\", \"doors\" : 4 }" +
        "    ,{ \"brand\" : \"Mercedes\", \"doors\" : 3}" +
        "    ,{ \"brand\" : \"BMW\",  \"doors\" : 2 }" +
        "  ]" +
        "}";

ObjectMapper mapper = JsonFactory.create();

Fleet fleet = mapper.fromJson(fleetStr, Fleet.class);

Map fleetMap = mapper.readValue(fleetStr, Map.class);
List<Map> carList = (List<Map>) fleetMap.get("cars");

for(Map carMap : carList){
    String brand = (String) carMap.get("brand");
    int    doors = (Integer)carMap.get("doors");

    System.out.println("brand: " + brand);
    System.out.println("doors: " + doors);
}

Parsing JSON From Other Sources

Boon can parse JSON from other sources than strings. You can parse also JSON from a:

  • byte array
  • char array
  • File
  • Reader
  • InputStream
  • String

Here is an example of parsing JSON from an InputStream:

Fleet fleet = mapper.readValue(
        new FileInputStream("data/fleet.json"), Fleet.class);

As you can see the InputStream is passed as the first parameter to the readValue() method of the ObjectMapper, instead of the JSON string used in the examples earlier in this tutorial.

If you want to parse JSON from another source, pass that source as the first parameter to the readValue() method instead.

Generating JSON From Objects

Boon can also generate JSON from objects using the Boon ObjectMapper. You generate JSON from an object by calling the writeValue() or writeValueAsString() methods of the Boon ObjectMapper.

The writeValueAsString() method takes an object as parameter and returns a string containing the JSON generated from the object. Here is an example of generating JSON using the writeValueAsString() method:

Fleet fleet   = new Fleet();
fleet.cars    = new Car[1];
fleet.cars[0] = new Car("Mercedes", 5);;

ObjectMapper mapper = JsonFactory.create();

String json = mapper.writeValueAsString(fleet);
System.out.println(json);

This example first creates a valid Fleet object with a Car object inside. Then it creates an ObjectMapper and calls the writeValueAsString() method. Finally the generated JSON is printed to System.out. The JSON generated from this example looks like this:

{"cars":[{"brand":"Mercedes","doors":5}]}

You can also write the generated JSON directly to a File, Writer or OutputStream. To do so you need to call the writeValue() method. Here is an example of how to write the generated JSON directly to an OutputStream:

mapper.writeValue(
         new FileOutputStream("data/output.json"),
         fleet);

To write the generated JSON to a File or a Writer, just pass a File or Writer as first parameter to the writeValue() method.

Generating JSON From Maps

The Boon ObjectMapper can also generate JSON from a Map. Just pass a Map instance as the second parameter to the writeValue() or writeValueAsString() method. Here is an example of generating a JSON string from a Map using the writeValueAsString() method:

Map car = new HashMap();
car.put("brand", "BMW");
car.put("doors", 4);

List cars = new ArrayList();
cars.add(car);

Map fleet = new HashMap();
fleet.put("cars", cars);

ObjectMapper mapper = JsonFactory.create();
String json = mapper.writeValueAsString(fleet);
System.out.println(json);

First the example creates a Map which represents a fleet object, and adds a list of cars (also represented by Map instances) to it. Second, the example creates an ObjectMapper and calls the writeValueAsString() method, passing the fleet Map as parameter. Finally the generated JSON String is printed out. The output from this code example would be:

{"cars":[{"doors":4,"brand":"BMW"}]}

You can also write the generated JSON directly to a File, Writer or OutputStream. Here is an example writing the generated JSON to an OutputStream, by calling the writeValue() method:

mapper.writeValue(
    new FileOutputStream("data/output-2.json"),
    fleet);

To write the generated JSON to a File or a Writer, just pass a File or Writer as first parameter to the writeValue() method.

Date Formats in JSON

The Boon ObjectMapper can work with different date formats in JSON. It can use parse and generate both a long version of a date (the number of milliseconds since jan. 1. 1970), or use the official JavaScript date format.

First, let us create a Java class that contains a Date object:

public class Payment {

    public Date paymentDate = null;

}

This Payment class only contains a single field, paymentDate, which is a java.util.Date instance.

Parsing a long Into a Date

Boon's ObjectMapper can parse a long value in JSON into a date. Here is a code example that:

String paymentJson = "{ \"paymentDate\" : 1434016456493 }";

ObjectMapper objectMapper = JsonFactory.create();

Payment payment = objectMapper.readValue(paymentJson, Payment.class);

Notice the JSON string at the beginning of the example. It contains a field named paymentDate and the value is a long representation of a date, in milliseconds.

When the ObjectMapper parses this JSON string it converts the long value of the paymentDate into a Date object, because the paymentDate field of the Payment class is a Date.

Parsing a Date String Into a Date

Boon can also parse a readable date string into a Date object. Here is the example from the previous section, with the date expressed as a date string instead of a long millisecond value:

String paymentJson = "{ \"paymentDate\" : \"2015-06-11T12:33:00.014Z\" }";

ObjectMapper objectMapper = JsonFactory.create();
//ObjectMapper objectMapper = JsonFactory.createUseJSONDates();

Payment payment = objectMapper.readValue(paymentJson, Payment.class);

System.out.println("payment.paymentDate = " + payment.paymentDate);

Generating Date Strings in JSON

By default the ObjectMapper will serialize a Date to a long number (milliseconds) when generating JSON from an object. However, you can create a version of the ObjectMapper which creates date strings instead. Here is how:

ObjectMapper objectMapper = JsonFactory.createUseJSONDates();

Once you have created an ObjectMapper using the createUseJSONDates() method instead of create() method of the JsonFactory class, Date fields will get converted to date strings in the serialized JSON instead of numbers.

Annotations

Boon contains a set of annotations that can be used to adjust the parsing or generation of JSON. These annotations are:

  • @JsonIgnore
  • @JsonInclude

These annotations will explained in the following sections:

@JsonIgnore

The @JsonIgnore annotation can be placed above a field in a class. When Boon detects the @JsonIgnore it will ignore that field. Here is an example class that uses the @JsonIgnore annotation :

import org.boon.json.annotations.JsonIgnore;

public class Car {

    public String brand = null;
    public int    doors = 0;

    @JsonIgnore
    public String comment = "blablabla";

    public Car() {}

    public Car(String brand, int doors) {
        this.brand = brand;
        this.doors = doors;
    }
}

When Boon detects the @JsonIgnore annotation attached to the comment field Boon will not serialize the comment field when serializing a Car object.

@JsonInclude

By default Boon excludes fields from serialization that are empty (null), empty lists, or fields which have default values (e.g. 0 for int and false for boolean etc.). If you want Boon to include such fields in the generated JSON, you can add a @JsonInclude annotation to the field. Here is an example class that uses the @JsonInclude annotation:

import org.boon.json.annotations.JsonIgnore;

public class Car {

    public String brand = null;
    public int    doors = 0;

    @JsonInclude
    public String comment = "blablabla";

    public Car() {}

    public Car(String brand, int doors) {
        this.brand = brand;
        this.doors = doors;
    }
}

Parsing Primitives

Boon can also parse fragments of JSON into Java primitives. For instance, parsing a string into an int or a JSON array into an array of Java primitives. This can be handy from time to time.

To use these primitive parsing features you need to access the JsonParserAndMapper returned from the ObjectMapper's parser method. On the JsonParserAndMapper instance you can call the primitive parsing methods.

Here is an example parsing a string into an int:

ObjectMapper objectMapper = JsonFactory.create();

int intVal = objectMapper.parser().parseInt("123");

The JsonParserAndMapper can also parse a JSON string representing an array of strings or numbers into an array of primitive Java types. Here is an example showing how to parse a JSON array into an array of int:

int[] ints = objectMapper.parser()
        .parseIntArray("[123, 456, 789]");

Similarly the JsonParserAndMapper can parse a JSON string representing an object into a Java Map, like this:

String jsonMap = "{ \"key1\" : \"val1\", \"key2\" : \"val2\" }";

Map<String, Object> map =
        objectMapper.parser().parseMap(jsonMap);

The JsonParserAndMapper has several more methods that can parse JSON strings and fragments into primitive Java types.

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next