Converting JSON to and From Java Object using Jackson
Converting JSON to and From Java Object using Jackson
In this tutorial we will discuss how to Convert JSON to and From Java Object using Jackson using databind ObjectMapper. We will discuss various different mechanisms at our disposal for performing these conversions.
What’s Covered
- Jackson Databind ObjectMapper
- Converting Java Object to JSON
- Converting Java Object to JSON using PrettyPrinter
- Converting JSON to Java Object
- Converting JSON to Java Object using Reader
- Converting JSON into Java HashMap using Reader
- Read JSON into JsonNode using String
- Read JSON from File
- Read JSON from InputStream
- Read JSON from InputStreamReader
- Read JSON from a URL
- Read JSON from a Byte Array
- Reviewing our Java Object Customer.class
Getting Started
In order to run this tutorial yourself, you will need the following:
- Java JDK 1.6 or greater
- Favorite IDE Spring Tool Suite (STS), Eclipse IDE or NetBeans (I happen to be using STS because it comes with a Tomcat server built-in)
- Tomcat 7 or greater or other popular container (Weblogic, Websphere, Glassfish, JBoss, VMWare vFabric, etc). For this tutorial I am using VMware vFabric tc Server Developer Edition which is essentially an enhanced Tomcat instance integrated with Spring STS
- Jackson Data Mapper Data Mapper package is a high-performance data binding package built on Jackson JSON processor
- Jackson Core Jackson is a high-performance JSON processor (parser, generator)
Required Libraries
In my example, I have copied the required libraries to the lib folder.
jackson-core-asl-1.9.13.jar jackson-mapper-asl-1.9.13.jar
You will then configure your libraries in the Libraries tab on Java Build Path Dialog Screen (shown below).

Complete Project Overview
I have added the project overview to give you a full view of the structure and show you all files contained in this sample project.

Jackson Databind ObjectMapper
Jackson’s Objectmapper provides the functionality for performing the actual conversions between Java Objects and JSON equivalents. The Jackson package contains many classes like ObjectMapper, JsonParser, and JsonGenerator. Using these classes we can read and write JSON from String, File, Streams, URLs, etc.
It performs the serialization (process of writing or converting the object to JSON) using the object’s “getter” methods; although it can be overridden by the @JsonGetter annotation. It also performs the opposite, using deserialization (process of writing or converting the JSON back to a Java Object) using the object’s “setter” methods; although it can be overridden by the @JsonSetter annotation.
Converting Java Object to JSON
In order to convert Java Objects (POJOs) to JSON we use one several methods available to us.
- writeValue()
- writeValueAsBytes()
- writeValueAsString()
In the following example, you will notice that I am using writeValueAsString() method which will serialize the Java Object into the JSON String equivalent. We pass our Java object (POJO), in our case, the customer instance, we want to serialize as the parameter to this method.
Customer customer = new Customer("001", "Amaury", "Valdes", "100 Main Street", "Newark", "New Jersey", "07044", "908-321-8080", "amaury.valdes@mail.com", "avaldes.com"); ObjectMapper mapper = new ObjectMapper(); String json = null; try { json = mapper.writeValueAsString(customer); System.out.println(json); } catch (IOException e) { e.printStackTrace(); }
Output of Converting Java Object to JSON
{"address":"100 Main Street","city":"Newark","state":"New Jersey", "customer-id":"001","first-name":"Amaury","last-name":"Valdes", "zip-code":"07044","phone-number":"908-321-8080", "email-address":"amaury.valdes@mail.com","company-name":"avaldes.com"}
Converting Java Object to JSON using PrettyPrinter
In this example, we use writerWithDefaultPrettyPrinter() to format the JSON output with indentation for a nicer JSON presentation.
// Java Object to JSON String using Pretty Printer Customer customer = new Customer("001", "Amaury", "Valdes", "100 Main Street", "Newark", "New Jersey", "07044", "908-321-8080", "amaury.valdes@mail.com", "avaldes.com"); ObjectMapper mapper = new ObjectMapper(); String json = null; try { json = mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(customer); System.out.println(json); } catch (IOException e) { e.printStackTrace(); }
Output of Converting Java Object to JSON Using PrettyPrint
{ "address" : "100 Main Street", "city" : "Newark", "state" : "New Jersey", "customer-id" : "001", "first-name" : "Amaury", "last-name" : "Valdes", "zip-code" : "07044", "phone-number" : "908-321-8080", "email-address" : "amaury.valdes@mail.com", "company-name" : "avaldes.com" }
Converting JSON to Java Object
Jackson’s ObjectMapper makes converting a JSON String very straight-forward and simple. We use the readValue method and pass the JSON string as the first parameter and use the class as the second parameter in the method. This process will deserialize the JSON back to its Java Object equivalent.
// Read JSON from String ObjectMapper mapper = new ObjectMapper(); String json = "{\"customer-id\": \"002\", " + "\"first-name\":\"David\", " + "\"last-name\":\"Guttenburg\", " + "\"address\":\"1029 Main Street\", " + "\"city\":\"Clifton\", " + "\"state\":\"New Jersey\", " + "\"zip-code\":\"07013\", " + "\"phone-number\":\"973-292-1828\", " + "\"email-address\":\"david@guttenburg.com\", " + "\"company-name\":\"Guttenburg Associates, LLC\"" + "}"; try { Customer cust = mapper.readValue(json, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); }
Output of JSON to Java Object
Customer [customerId=002, firstName=David, lastName=Guttenburg, address=1029 Main Street, city=Clifton, state=New Jersey, zipCode=07013, phoneNumber=973-292-1828, emailAddress=david@guttenburg.com, companyName=Guttenburg Associates, LLC]
Converting JSON to Java Object using Reader
In this next example, we show you how Jackson can perform the deserialization from JSON to Java objects using a Reader, which is the abstract class for all of the Readers in the Java IO API. Subclasses include BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, and StringReader.
In this example, we are using the StringReader which reads a character stream where the source is a String.
// Read JSON from Reader ObjectMapper mapper = new ObjectMapper(); String json = "{\"customer-id\": \"003\", " + "\"first-name\":\"Jennifer\", \"last-name\":\"Wilson\"}"; Reader reader = new StringReader(json); try { Customer cust = mapper.readValue(reader, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); }
Output of Converting JSON to Java Object using Reader
Customer [customerId=002, firstName=Jennifer, lastName=Wilson, address=null, city=null, state=null, zipCode=null, phoneNumber=null, emailAddress=null, companyName=null]
Converting JSON into Java HashMap
In this next example, we show you how Jackson can perform the deserialization from JSON into Java HashMap. We use the readValue method and pass the JSON string as the first parameter and use the HaspMap class as the second parameter in the method. Once the JSON has been deserialized, we will are able to access field by field in a simple and highly efficient manner.
// Read JSON From a URL try { URL myUrl = new URL("https://avaldes.com/data/customer7.json"); HashMap fields = mapper.readValue(myUrl, HashMap.class); System.out.println("customer-id......: " + fields.get("customer-id")); System.out.println("first-name.......: " + fields.get("first-name")); System.out.println("last-name........: " + fields.get("last-name")); System.out.println("address..........: " + fields.get("address")); System.out.println("state............: " + fields.get("state")); System.out.println("zip-code.........: " + fields.get("zip-code")); System.out.println("phone-number.....: " + fields.get("phone-number")); System.out.println("email-address....: " + fields.get("email-address")); System.out.println("company-name.....: " + fields.get("company-name")); } catch (IOException e) { e.printStackTrace(); }
Output of Converting JSON to Java HashMap
customer-id......: 007 first-name.......: Deven last-name........: Brown address..........: 123 Mount Prospect Avenue state............: New Jersey zip-code.........: 08718 phone-number.....: 800-555-8888 email-address....: deven.brown@wehaulit.com company-name.....: WeHaulIT!
Read JSON into JsonNode using String
The JsonNode is the base class for all JSON nodes in the Jackson Databind package, which forms the basis of JSON Tree Model that Jackson implements. One can think of these nodes somewhat akin to DOM nodes in XML DOM trees.
We can use this mechanism when we do not have a java class to put our JSON string into. In this case, we can use the JsonNode as a generic container we can deserialize our JSON string into.
// Read JSON into JsonNode using String ObjectMapper mapper = new ObjectMapper(); String json = "{\"customer-id\": \"003\", \"first-name\":" + "\"Amanda\", \"last-name\":\"Freeman\"}"; try { JsonNode node = mapper.readTree(json); System.out.println(node); } catch (IOException e) { e.printStackTrace(); }
Output of Reading JSON into JsonNode using String
{"customer-id":"003","first-name":"Amanda","last-name":"Freeman"}
Read JSON from File
So far you have seen how ObjectMapper is able to use String, Readers like (StringReader, InputStreamReader, FileReader, etc), but in this example we will be using File class.
customer5.json
{ "customer-id": "005", "first-name": "Robert", "last-name": "Smith", "address": "123 Passaic Street", "city": "Passaic", "state": "New Jersey", "zip-code": "07055", "phone-number": "800-555-1212", "email-address": "robert.smith@gmail.com", "company-name": "Google Services" }
// Read JSON From File try { File file = new File("resources/customer5.json"); Customer cust = mapper.readValue(file, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); }
Output of Reading JSON from File
Customer [customerId=005, firstName=Robert, lastName=Smith, address=123 Passaic Street, city=Passaic, state=New Jersey, zipCode=07055, phoneNumber=800-555-1212, emailAddress=robert.smith@gmail.com, companyName=Google Services]
Read JSON from InputStream
In our next example of reading JSON from an InputStream, you will notice how easily one can do it using Jackson’s ObjectMapper class.
customer6.json
{ "address": "300 Mount Laurel Avenue", "city": "Middletown", "state": "New Jersey", "customer-id": "006", "first-name": "Marisa", "last-name": "Smith", "zip-code": "08272", "phone-number": "800-555-1212", "email-address": "marisa.smith@gmail.com", "company-name": "SelfServices" }
// Read JSON From InputStream try { InputStream inStream = new FileInputStream( "resources/customer6.json"); Customer cust = mapper.readValue(inStream, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); }
Output of Reading JSON from InputStream
Customer [customerId=006, firstName=Marisa, lastName=Smith, address=300 Mount Laurel Avenue, city=Middletown, state=New Jersey, zipCode=08272, phoneNumber=800-555-1212, emailAddress=marisa.smith@gmail.com, companyName=SelfServices]
Read JSON from InputStreamReader
An InputStreamReader allows us to read characters from files; It reads bytes and decodes them into characters using a specified charset. The InputStreamReader may read one or more bytes from the underlying byte-input stream, usually an InputStream.
For this example, we will be using the same file that we used in our previous example. But as you can see, using InputStreamReader is quite a simple process.
/ Read JSON From InputStreamReader try { InputStream inStream = new FileInputStream( "resources/customer6.json"); InputStreamReader inReader = new InputStreamReader(inStream, "UTF-8"); Customer cust = mapper.readValue(inReader, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); }
Output of Reading JSON from InputStreamReader
Customer [customerId=006, firstName=Marisa, lastName=Smith, address=300 Mount Laurel Avenue, city=Middletown, state=New Jersey, zipCode=08272, phoneNumber=800-555-1212, emailAddress=marisa.smith@gmail.com, companyName=SelfServices]
Read JSON from a URL
Jackson ObjectMapper’s readValue also supports reading from and URL using java.net.URL.
// Read JSON From a URL try { URL myUrl = new URL("https://avaldes.com/data/customer7.json"); Customer cust = mapper.readValue(myUrl, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); }
Output of Read JSON from a URL
Customer [customerId=007, firstName=Deven, lastName=Brown, address=123 Mount Prospect Avenue, city=Newark, state=New Jersey, zipCode=08718, phoneNumber=800-555-8888, emailAddress=deven.brown@wehaulit.com, companyName=WeHaulIT!]
Read JSON from a Byte Array
In this example, we see how Jackson converts a byte array into a Java object. Here we see how we can read JSON from a byte array and deserialize it:
// Read JSON from ByteArray json = "{\"customer-id\": \"008\", " + "\"first-name\":\"Leslie\", " + "\"last-name\":\"Winterfield\", " + "\"address\":\"87 River Road\", " + "\"city\":\"Clifton\", " + "\"state\":\"New Jersey\", " + "\"zip-code\":\"07013\", " + "\"phone-number\":\"973-779-0293\", " + "\"email-address\":\"leslie@mail.com\", " + "\"company-name\":\"USPS Clifton\"" + "}"; try { byte myByteArray[] = json.getBytes("UTF-8"); Customer cust = mapper.readValue(myByteArray, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); }
Output of Read JSON from a Byte Array
Customer [customerId=008, firstName=Leslie, lastName=Winterfield, address=87 River Road, city=Clifton, state=New Jersey, zipCode=07013, phoneNumber=973-779-0293, emailAddress=leslie@mail.com, companyName=USPS Clifton]
The Customer Model (Customer.java)
This will be used to as the object which we store and retrieve in order to test out our application. I added it because I wanted my web service to store and retrieve some Java object.
package com.avaldes.model; import org.codehaus.jackson.annotate.JsonProperty; public class Customer { private String customerId; private String firstName; private String lastName; private String address; private String city; private String state; private String zipCode; private String phoneNumber; private String emailAddress; private String companyName; public Customer() { } public Customer(String customerId, String firstName, String lastName, String address, String city, String state, String zipCode, String phoneNumber, String emailAddress, String companyName) { this.customerId = customerId; this.firstName = firstName; this.lastName = lastName; this.address = address; this.city = city; this.state = state; this.zipCode = zipCode; this.phoneNumber = phoneNumber; this.emailAddress = emailAddress; this.companyName = companyName; } @JsonProperty("customer-id") public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } @JsonProperty("first-name") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @JsonProperty("last-name") public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @JsonProperty("address") public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @JsonProperty("city") public String getCity() { return city; } public void setCity(String city) { this.city = city; } @JsonProperty("state") public String getState() { return state; } public void setState(String state) { this.state = state; } @JsonProperty("zip-code") public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } @JsonProperty("phone-number") public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } @JsonProperty("email-address") public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } @JsonProperty("company-name") public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } @Override public String toString() { return "Customer [customerId=" + customerId + ", firstName=" + firstName + ", lastName=" + lastName + ", address=" + address + ", city=" + city + ", state=" + state + ", zipCode=" + zipCode + ", phoneNumber=" + phoneNumber + ", emailAddress=" + emailAddress + ", companyName=" + companyName + "]"; } }
Complete Program (JsonToObjectExample.java)
package com.avaldes.tutorial; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URL; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import com.avaldes.model.Customer; public class JsonToObjectExample { public static void main(String[] args) { // Java Object to JSON String Customer customer = new Customer("001", "Amaury", "Valdes", "100 Main Street", "Newark", "New Jersey", "07044", "908-321-8080", "amaury.valdes@mail.com", "avaldes.com"); ObjectMapper mapper = new ObjectMapper(); String json = null; try { json = mapper.writeValueAsString(customer); System.out.println(json); } catch (IOException e) { e.printStackTrace(); } // Java Object to JSON String Pretty Print try { json = mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(customer); System.out.println(json); } catch (IOException e) { e.printStackTrace(); } // Read JSON from String json = "{\"customer-id\": \"002\", " + "\"first-name\":\"David\", " + "\"last-name\":\"Guttenburg\", " + "\"address\":\"1029 Main Street\", " + "\"city\":\"Clifton\", " + "\"state\":\"New Jersey\", " + "\"zip-code\":\"07013\", " + "\"phone-number\":\"973-292-1828\", " + "\"email-address\":\"david@guttenburg.com\", " + "\"company-name\":\"Guttenburg Associates, LLC\"" + "}"; try { Customer cust = mapper.readValue(json, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); } // Read JSON from Reader json = "{\"customer-id\": \"003\", " + "\"first-name\":\"Jennifer\", \"last-name\":\"Wilson\"}"; Reader reader = new StringReader(json); try { Customer cust = mapper.readValue(reader, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); } // Read JSON into JsonNode using String json = "{\"customer-id\": \"004\", " + "\"first-name\":\"Amanda\", " + "\"last-name\":\"Freeman\"}"; try { JsonNode node = mapper.readTree(json); System.out.println(node); } catch (IOException e) { e.printStackTrace(); } // Read JSON From File try { File file = new File("resources/customer5.json"); Customer cust = mapper.readValue(file, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); } // Read JSON From InputStream try { InputStream inStream = new FileInputStream( "resources/customer6.json"); Customer cust = mapper.readValue(inStream, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); } // Read JSON From InputStreamReader try { InputStream inStream = new FileInputStream( "resources/customer6.json"); InputStreamReader inReader = new InputStreamReader(inStream, "UTF-8"); Customer cust = mapper.readValue(inReader, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); } // Read JSON From a URL try { URL myUrl = new URL("https://avaldes.com/data/customer7.json"); Customer cust = mapper.readValue(myUrl, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); } // Read JSON From a URL into HashMap try { URL myUrl = new URL("https://avaldes.com/data/customer7.json"); @SuppressWarnings("rawtypes") HashMap fields = mapper.readValue(myUrl, HashMap.class); System.out.println("customer-id......: " + fields.get("customer-id")); System.out.println("first-name.......: " + fields.get("first-name")); System.out.println("last-name........: " + fields.get("last-name")); System.out.println("address..........: " + fields.get("address")); System.out.println("state............: " + fields.get("state")); System.out.println("zip-code.........: " + fields.get("zip-code")); System.out.println("phone-number.....: " + fields.get("phone-number")); System.out.println("email-address....: " + fields.get("email-address")); System.out.println("company-name.....: " + fields.get("company-name")); } catch (IOException e) { e.printStackTrace(); } // Read JSON from ByteArray json = "{\"customer-id\": \"008\", " + "\"first-name\":\"Leslie\", " + "\"last-name\":\"Winterfield\", " + "\"address\":\"87 River Road\", " + "\"city\":\"Clifton\", " + "\"state\":\"New Jersey\", " + "\"zip-code\":\"07013\", " + "\"phone-number\":\"973-779-0293\", " + "\"email-address\":\"leslie@mail.com\", " + "\"company-name\":\"USPS Clifton\"" + "}"; try { byte myByteArray[] = json.getBytes("UTF-8"); Customer cust = mapper.readValue(myByteArray, Customer.class); System.out.println(cust); } catch (IOException e) { e.printStackTrace(); } // Write Object to File try { Customer customer9 = new Customer("009", "Jessica", "Alba", "87 Woods Road", "Selena", "California", "31003", "800-837-9300", "jessica@alba.com", "alba.com"); System.out .println("Writing to resources/customer9-out.json..."); File file = new File("resources/customer9-out.json"); mapper.writeValue(file, customer9); } catch (IOException e) { e.printStackTrace(); } // Write Object to FileOutputStream OutputStream outStream = null; try { Customer customer3 = new Customer("010", "Marisa", "Roberts", "283 Randolph Street", "Princeton", "New Jersey", "07029", "888-229-9989", "marisa.roberts@lba.com", "lba.com"); System.out .println("Writing to resources/customer10-out.json..."); File file = new File("resources/customer10-out.json"); outStream = new FileOutputStream(file); mapper.writeValue(outStream, customer3); } catch (IOException e) { e.printStackTrace(); } finally { try { outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Download the Complete Source Code
That’s It!
I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

Please Share Us on Social Media






Leave a Reply