• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Jackson 2 JSON Parser – Convert JSON to/from Java Object

November 6, 2016 by javainterviewpoint Leave a Comment

In this Jackson 2 JSON Parser example we will learn how to Convert JSON to Java object and Convert Java Object to JSON again using Jackson 2 API.

Folder Structure:

Jackson 2 JSON Parser

    1. Create a new Java Project  “JacksonJSONTutorial” and create a package for our src files “com.javainterviewpoint“
    2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.

commons-io-2.5.jar
jackson-databind.2.8.4.jar

if you are running on maven add the below dependency to your pom.xml

 <dependencies>
  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.8.4</version>
 </dependency>
 <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.5</version>
  </dependency>
 </dependencies>
  1. Create the Java classes JSONReader.java, JSONWriter.java and StudentDetails.java under  com.javainterviewpoint folder.

Other Posts which you may like …

  • Jackson 2 JSON Parser – Convert JSON to/from Java Object
  • How to Convert JSON to / from Java Map using JACKSON
  • Jackson Tree Model Example – JsonNode
  • Jackson Streaming API Example | Read and Write JSON
  • Jackson JSON Example | ObjectMapper and @JSONView
  • How to Parse JSON to/from Java Object using Boon JSON Parser
  • How to Read and Write JSON using GSON
  • How to write JSON object to File in Java?
  • How to read JSON file in Java – JSONObject and JSONArray
  • Jersey Jackson JSON Tutorial
  • Spring REST Hello World Example – JSON and XML responses
  • How to Convert Java Object to JSON using JAXB
  • JAX-RS REST @Consumes both XML and JSON Example
  • JAX-RS REST @Produces both XML and JSON Example

Jackson 2 JSON Parser

To Convert JSON to Java object and Convert Java Object to JSON again. We will be using this JSON file.

JSON file content(StudentDetails.json)

{
   "id":999,
   "name":"JavaInterviewPoint",
   "department":"ComputerScience",
   "favoriteSports":["Cricket","Tennis","Football"]
}

StudentDetails.java

A simple POJO, for holding the details of the Student.

package com.javainterviewpoint;

import java.util.List;

public class StudentDetails
{
    private int id;
    private String name;
    private String department;
    private List favoriteSports;

    public StudentDetails()
    {}

    public StudentDetails(int id, String name, String department,
            List favoriteSports)
    {
        this.id = id;
        this.name = name;
        this.department = department;
        this.favoriteSports = favoriteSports;
    }

    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getDepartment()
    {
        return department;
    }
    public void setDepartment(String department)
    {
        this.department = department;
    }
    public List getFavoriteSports()
    {
        return favoriteSports;
    }
    public void setFavoriteSports(List favoriteSports)
    {
        this.favoriteSports = favoriteSports;
    }
}

Convert JSON to Java object

package com.javainterviewpoint;

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

import org.apache.commons.io.FileUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONReader 
{
    public static void main(String[] args)
    {
        String data="";
        //Create a new ObjectMapper, for mapping data to POJO
        ObjectMapper mapper = new ObjectMapper();
        
        try
        {
            //Read the StudentDetails.json
            data = FileUtils.readFileToString(new File("c:\\StudentDetails.json"));
            //Read and map data to studentDetails object
            StudentDetails studentDetails = mapper.readValue(data, StudentDetails.class);
            //Print the studentdetails
            System.out.println("*** StudentDetails Details ***");
            System.out.println("Student Name        : "+studentDetails.getName());
            System.out.println("Student Id          : "+studentDetails.getId());
            System.out.println("Student Department  : "+studentDetails.getDepartment());
            System.out.println("Favourite Sports : ");
            for(String fav : studentDetails.getFavoriteSports())
            {
                System.out.print(fav +" | ");
            }
        } catch (JsonParseException e)
        {
            e.printStackTrace();
        } catch (JsonMappingException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
  • Create a new ObjectMapper object, it helps us mapping the JSON data with the POJO
ObjectMapper mapper = new ObjectMapper();
  • Using the apache commons.io, read the “StudentDetails.json” file. You can also read the file with any Java File Reader such as BufferedReader
data = FileUtils.readFileToString(new File("c:\\StudentDetails.json"));
  • The readValue() method of the ObjectMapper class converts the JSON String into Java Object and maps it to the POJO. It takes two parameters data (JSON String) and the POJO class(StudentDetails.class)
StudentDetails studentDetails = mapper.readValue(data, StudentDetails.class);
  • Finally, print the Student details
 System.out.println("*** StudentDetails Details ***");
 System.out.println("Student Name        : "+studentDetails.getName());
 System.out.println("Student Id          : "+studentDetails.getId());
 System.out.println("Student Department  : "+studentDetails.getDepartment());
 System.out.println("Favourite Sports : ");
 for(String fav : studentDetails.getFavoriteSports())
 {
      System.out.print(fav +" | ");
 }

Output : 

*** StudentDetails Details ***
Student Name        : JavaInterviewPoint
Student Id          : 999
Student Department  : ComputerScience
Favourite Sports : 
Cricket | Tennis | Football

 

Convert Java Object to JSON

package com.javainterviewpoint;

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

import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONWriter 
{
    public static void main(String[] args)
    {
        try 
        {
            //Create a new StudentDetails object
            StudentDetails studentDetails = new StudentDetails();
            //set value to its properties
            studentDetails.setName("JavaInterviewPoint");
            studentDetails.setId(1);
            studentDetails.setDepartment("Science");
            
            List favoriteSports = new ArrayList();
            favoriteSports.add("Cricket");
            favoriteSports.add("Tennis");
            favoriteSports.add("Football");
                        
            studentDetails.setFavoriteSports(favoriteSports);
            //Create a new ObjectMapper, for mapping data to POJO
            ObjectMapper mapper = new ObjectMapper();
            //Set prettyprint option
            mapper.writerWithDefaultPrettyPrinter();
            //Write the studentDetails data into StudentDetails.json
            mapper.writeValue(new File("c://StudentDetails.json"), studentDetails);
            System.out.println("JSON Write successful!!");
            
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
  • Create a new Object for the StudentDetails class
StudentDetails studentDetails = new StudentDetails();
  • Set value to the properties of StudentDetails
StudentDetails studentDetails = new StudentDetails();
studentDetails.setName("JavaInterviewPoint");
studentDetails.setId(1);
studentDetails.setDepartment("Science");
  • Create a new ObjectMapper object, it helps us mapping the JSON data with the POJO
ObjectMapper mapper = new ObjectMapper();
  • Using the writeValue() method of the ObjectMapper class, write the studentDetails object into StudentDetails.json.
mapper.writeValue(new File("c://StudentDetails.json"), studentDetails);

Output :

{
 "id":1,
 "name":"JavaInterviewPoint",
 "department":"Science",
 "favoriteSports":["Cricket","Tennis","Football"]
}

Filed Under: J2EE, Java, JSON Tagged With: Jackson 2, Jackson 2 JSON Parser, JSON parser

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·