­
:::: MENU ::::

Jackson JSON


Jackson is a tool that allows, amonth other things, to transform Java object to JSON objects and viceversa. We are going to create a project to demonstrate how this technology works.

Project creation

We create a Maven project.

Jackson libraries import

We have to update the pom.xml file and add the following dependencies:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.3</version>
</dependency>

Mapper object

Jackson gives us a mapper object that we will use to perform the tansformations. This is the ObjectMapper.

1
ObjectMapper mapper = new ObjectMapper();

Java Bean example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package app;
 
public class MyObject {
    private String myString;
    private int myInt;
 
    public MyObject() {
        super();
    }
 
    public MyObject(String myString, int myInt) {
        super();
        this.myString = myString;
        this.myInt = myInt;
    }
 
    public String getMyString() {
        return myString;
    }
 
    public void setMyString(String myString) {
        this.myString = myString;
    }
 
    public int getMyInt() {
        return myInt;
    }
 
    public void setMyInt(int myInt) {
        this.myInt = myInt;
    }
 
    @Override
    public String toString() {
        return "MyObject [myString=" + myString + ", myInt=" + myInt + "]";
    }
 
}

We are going to use a JSON object that we will transform into a Java object. We will transform this last Java object to a JSON object.

JSON to Java transformation

In our case we are going to use a JSON text string. It is very simple to do so:

1
2
String jsonInputString = "{\"myString\":\"abc\", \"myInt\":123}";
MyObject myObject = mapper.readValue(jsonInputString, MyObject.class);

Java to JSON transformation

It is also simple:

1
String jsonOutputString = mapper.writeValueAsString(myObject);

The code of this project is situated at https://github.com/luisgomezcaballero/jackson-json.


So, what do you think ?