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:
<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.
ObjectMapper mapper = new ObjectMapper();
Java Bean example
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:
String jsonInputString = "{\"myString\":\"abc\", \"myInt\":123}"; MyObject myObject = mapper.readValue(jsonInputString, MyObject.class);
Java to JSON transformation
It is also simple:
String jsonOutputString = mapper.writeValueAsString(myObject);
The code of this project is situated at https://github.com/luisgomezcaballero/jackson-json.
So, what do you think ?