Parse JSON Data in Java Using Jackson Library

In this tutorial, you’ll learn how to parse JSON in Java with Jackson, one of the most popular JSON libraries in the Java ecosystem.. We’ll walk through two practical examples involving a shopping list and a Person’s profile. We’ll cover everything step-by-step with clearly explained code examples.

What is Jackson?

Jackson is a powerful JSON library for Java that allows you to parse JSON into Java objects and vice versa. It is widely used due to its speed and ease of use.

Project Setup

Step 1: Create a Maven Project

Step 2 : Add the following dependency in the pom.xml

<dependencies>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.18.4</version>
        </dependency>
</dependencies>

Project 1: Parse Shopping List JSON in Java with Jackson

JSON file used:

{
    "shoppingList": {
      "groceries": [
        {
          "item": "Apples",
          "quantity": 3,
          "unit": "lbs"
        },
        {
            "item": "Grapes",
            "quantity": 2,
            "unit": "lbs"
          },

        {
          "item": "Bread",
          "quantity": 2,
          "unit": "loaves"
        },
        {
          "item": "Milk",
          "quantity": 1,
          "unit": "gallon"
        },
        {
          "item": "Eggs",
          "quantity": 1,
          "unit": "dozen"
        },
        {
          "item": "Chicken",
          "quantity": 2,
          "unit": "lbs"
        },
        {
            "item": "Meat",
            "quantity": 1,
            "unit": "lbs"
        },
        {
            "item": "Tomato",
            "quantity": 2,
            "unit": "lbs"
        }
      ],
      "personalCare": [
        {
          "item": "Toothpaste",
          "quantity": 2,
          "unit": "packs"
        },
        {
          "item": "Shampoo",
          "quantity": 1,
          "unit": "bottle"
        },
        {
          "item": "Soap",
          "quantity": 3,
          "unit": "bars"
        },
        {
          "item": "Toilet Paper",
          "quantity": 1,
          "unit": "pack"
        }
      ],
      "householdItems": [
        {
          "item": "Paper Towels",
          "quantity": 4,
          "unit": "rolls"
        },
        {
          "item": "Laundry Detergent",
          "quantity": 1,
          "unit": "container"
        },
        {
          "item": "Trash Bags",
          "quantity": 2,
          "unit": "boxes"
        },
        {
          "item": "Batteries",
          "quantity": 1,
          "unit": "pack"
        }
      ]
    }
}
Step 1: Create a POJO Classes

We will create java classes to represent the json.

1)Item.java

package org.example2;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Item {

    @JsonProperty("item")
    private String item;

    @JsonProperty("unit")
    private String unit;

    @JsonProperty("quantity")
    private int quantity;

    public String getItems() {
        return item;
    }

    public void setItems(String item) {
        this.item = item;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public String getUnit() {
        return unit;
    }

    public void setUnit(String unit) {
        this.unit = unit;
    }
}

This class represents each item in the shopping list. Since our JSON uses the exact field names, we don’t need to use annotations like @JsonProperty.

2)ShoppingList.java
package org.example2;

import java.util.List;

public class ShoppingList {

    private List<Item> groceries;

    private List<Item>personalCare;

    private List<Item> householdItems;

    public List<Item> getGroceries() {
        return groceries;
    }

    public void setGroceries(List<Item> groceries) {
        this.groceries = groceries;
    }

    public List<Item> getHouseholdItems() {
        return householdItems;
    }

    public void setHouseholdItems(List<Item> householdItems) {
        this.householdItems = householdItems;
    }

    public List<Item> getPersonalCare() {
        return personalCare;
    }

    public void setPersonalCare(List<Item> personalCare) {
        this.personalCare = personalCare;
    }
}

This class groups the three categories under the shoppingList key in the JSON.

3)Shopping.java
package org.example2;


public class Shopping {
    private ShoppingList shoppingList;

    public ShoppingList getShoppingList() {
        return shoppingList;
    }

    public void setShoppingList(ShoppingList shoppingList) {
        this.shoppingList = shoppingList;
    }
}

This class represents the root of our JSON structure.

Step2:Read JSON Using Jackson
package org.example2;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.List;


        public class Main {
            public static void main(String[] args) throws IOException {

                ObjectMapper mapper = new ObjectMapper();
                File path = new File("Enter the path of the json file in your system");
                Shopping shopping = mapper.readValue(path, Shopping.class);

                ShoppingList shoplist = shopping.getShoppingList();

                printCategory("List of Groceries", shoplist.getGroceries());
                printCategory("List of Personal Care", shoplist.getPersonalCare());
                printCategory("List of Household Items", shoplist.getHouseholdItems());


            }

            private static void printCategory(String title, List<Item> items) {
                System.out.println("\n------------------------- " + title + " -------------------------");
                System.out.printf("%-5s %-20s %-10s %-10s%n", "No.", "Item", "Quantity", "Unit");
                System.out.println("---------------------------------------------------------------");

                int count = 1;
                for (Item i : items) {
                    System.out.printf("%-5d %-20s %-10d %-10s%n",
                            count, i.getItems(), i.getQuantity(), i.getUnit());
                    count++;
                }
            }
        }


Output:
------------------------- List of Groceries -------------------------
No.   Item                 Quantity   Unit      
---------------------------------------------------------------
1     Apples               3          lbs       
2     Grapes               2          lbs       
3     Bread                2          loaves    
4     Milk                 1          gallon    
5     Eggs                 1          dozen     
6     Chicken              2          lbs       
7     Meat                 1          lbs       
8     Tomato               2          lbs       

------------------------- List of Personal Care -------------------------
No.   Item                 Quantity   Unit      
---------------------------------------------------------------
1     Toothpaste           2          packs     
2     Shampoo              1          bottle    
3     Soap                 3          bars      
4     Toilet Paper         1          pack      

------------------------- List of Household Items -------------------------
No.   Item                 Quantity   Unit      
---------------------------------------------------------------
1     Paper Towels         4          rolls     
2     Laundry Detergent    1          container 
3     Trash Bags           2          boxes     
4     Batteries            1          pack      

 

Code Explanation:

We create an instance of ObjectMapper, the core class for working with JSON in Jackson. We then read the JSON file and map it to our Shopping class. After retrieving the shoppingList, we print each category using a helper method.

Project 2:Parse Person Profile JSON in Java Using Jackson

JSON file used:

{

    "name": "John",
    "age": 25,
    "married": false,
    "hobbies": ["reading", "traveling", "programming"],
    "address": {
      "street": "123 Main Street",
      "city": "Sample City",
      "postal_code": "12345"
    }
  }
Step 1: Create POJO Classes

Same as previous project we will create POJO classes to represent JSON

1)Person.java

package org.example1;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;

public class Person {

    private String name;

    private int age;

    @JsonProperty("married")
    private boolean ismarried;

    private List<String> hobbies;

    private Address address;

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getHobbies() {
        return String.join(" , ",hobbies);
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }

    public boolean isIsmarried() {
        return ismarried;
    }

    public void setIsmarried(boolean ismarried) {
        this.ismarried = ismarried;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }



}

2)Address.java

package org.example1;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Address {

    String city;

    @JsonProperty("postal_code")
    String postalCode;

    String street;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public void setPostalCode(String postalCode) {
        this.postalCode = postalCode;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String toString(){
        return getStreet() + " " + getCity() + " " + getPostalCode();
    }
}
Step2:Reading the JSON File
package org.example1;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {

        ObjectMapper objectMapper = new ObjectMapper();

        File file = new File(Enter the path of json file in your system);

        Person person  = objectMapper.readValue(file,Person.class);

        System.out.println("--------------------------------Person Details-----------------------------------------------");
        System.out.println("Name    : " + person.getName());
        System.out.println("Age     : " + person.getAge());
        if(person.isIsmarried())
            System.out.println("Married : " + "Yes");
        else System.out.println("Married : " + "No");
        System.out.println("Hobbies : " + person.getHobbies());
        System.out.println("Address : " + person.getAddress().toString());
    }
}
Output:
--------------------------------Person Details--------------------------------
Name    : John
Age     : 25
Married : No
Hobbies : reading , traveling , programming
Address : 123 Main Street Sample City 12345
Code Explanation:
  • We create an ObjectMapper instance.
  • We point it to the JSON file path on the disk.
  • readValue() reads and converts the JSON into a Person object.
  • We use getter methods like getName(), getAge(), isIsmarried() to fetch individual fields.
  • We use toString() of the Address object to print address information.
  • A conditional check prints “Yes” if the person is married and “No” otherwise.

Checkout other tutorials:

How to Read and Write Files in Java Using FileReader and FileWriter

Encryption and Decryption Of Data in Java Using AES Algorithm

How to Create Custom Annotations in Java (With Real-World Example)

Parse JSON Data in C++ Using nlohmann/json Library

How to Parse XML Data in Java Using DOM Parser

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top