Using Jackson 2.x for JSON in Java

Jackson is a JSON Processor Java Library. It is now on version 2.1.3 (as of Feb 26th 2013)- and has migrated from Codehaus to GitHub. The current homepage is fasterxml.com for the lastest information.

The download information has the listing of the latest version.

For Maven usage, there are three core jars that should be included:

  • Annotations
  • Core
  • Databind

<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>

Using it for a POJO

A working example is to have some JSON data in the form:

{"Name":"An appropriate title","Categoryid":"1"}

A key thing to note here is that the first element (Name) is capitalised. Typically in Java the Java Bean convention is used – so that if you have name – then getName() and setName() are the method that are going to be associated with the JSON object.

A first pass at the POJO would look like:

private String name;
public String categoryId;

This will result in an error:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Name" (class YOUR_CLASS_NAME_HERE), not marked as ignorable (2 known properties: , "CategoryId", "name"])

This means that we have to adjust the string that we are using to obtain the JSON object ( a string : value)- so that we use the appropriate capitalisation.
This can be done with the annotation

@JsonProperty

The relevant import is:

import com.fasterxml.jackson.annotation.*;


@JsonProperty("Name")
private String name;
@JsonProperty("Categoryid")
public String categoryId;

Useful sites:

http://jsonlint.com/ – a JSON validator (cut and past into the site).

References:

Advertisements
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s