• 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 JSON Example | ObjectMapper and @JSONView

September 30, 2016 by javainterviewpoint Leave a Comment

Jackson JSON Parser is a very popular JSON Java Parser, which can easily transform Java Objects to JSON and vice versa and Jackson API even provides default mapping for most of the objects which need to be serialized. In my previous articles, we have learnt How to Read a JSON in Java and How to write JSON object to File using GSON and JSON.simple API.  In this Jackson JSON Example, let’s see  how to use Jackson API to read JSON file and Write a JSON file.

Folder Structure:

    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-core-asl-1.9.13.jar
jackson-mapper-asl-1.9.13.jar

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

 <dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-core-asl</artifactId>
   <version>1.9.13</version>
</dependency>
<dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-mapper-asl</artifactId>
   <version>1.9.13</version>
</dependency>
<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.5</version>
</dependency>
  1. Create the Java classes Jackson_JSON_Reader.java, Jackson_JSON_Writer.java and UserDetails.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 JSON Example

For our Example of Convert JSON to Java object and Convert Java Object to JSON again. We will be using this JSON file.

JSON file content(test.json)

{ 
 "name" : "JavaInterviewPoint", 
 "age" : 999, 
 "favoriteSports" : [ "Football", "Cricket", "Tennis","Basket Ball"] 
}

UserDetail.java

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

package com.javainterviewpoint;

import java.util.List;

public class UserDetails
{
    private String name;
    private int age;
    private List favoriteSports;
    
    public UserDetails()
    {
        super();
    }
    public UserDetails(String name, int age, List favoriteSports)
    {
        super();
        this.name = name;
        this.age = age;
        this.favoriteSports = favoriteSports;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    public List getFavoriteSports()
    {
        return favoriteSports;
    }
    public void setFavoriteSports(List favoriteSports)
    {
        this.favoriteSports = favoriteSports;
    }
}

Jackson JSON Reader

package com.javainterviewpoint;

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

import org.apache.commons.io.FileUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class Jackson_JSON_Reader
{
    public static void main(String[] args)
    {
        String data="";
        //Create a new ObjectMapper, for mapping data to POJO
        ObjectMapper mapper = new ObjectMapper();
        
        try
        {
            //Read the test.json
            data = FileUtils.readFileToString(new File("c:\\test.json"));
            //Read and map data to userDetails object
            UserDetails userDetails = mapper.readValue(data, UserDetails.class);
            //Print the userdetails
            System.out.println("*** User Details ***");
            System.out.println("User Name : "+userDetails.getName());
            System.out.println("User Age  : "+userDetails.getAge());
            System.out.println("Favourite Sports : ");
            for(String fav : userDetails.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 “test.json” file. You can also read the file with any Java File Reader such as BufferedReader
data = FileUtils.readFileToString(new File("c:\\test.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(UserDetails.class)
UserDetails userDetails = mapper.readValue(data, UserDetails.class);
      • Finally, print the user details
System.out.println("*** User Details ***");
System.out.println("User Name : "+userDetails.getName());
System.out.println("User Age  : "+userDetails.getAge());
System.out.println("Favourite Sports : ");
for(String fav : userDetails.getFavoriteSports())
    {
       System.out.print(fav +" | ");
    }

Output : 

Jackson JSON Example

Jackson JSON Writer

package com.javainterviewpoint;

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

import org.codehaus.jackson.map.ObjectMapper;

public class Jackson_JSON_Writer
{
    public static void main(String[] args)
    {
        try 
        {
            //Create a new UserDetails object
            UserDetails userDetails = new UserDetails();
            //set value to its properties
            userDetails.setName("Java");
            userDetails.setAge(111);
            
            List favoriteSports = new ArrayList();
            favoriteSports.add("BaseBall");
            favoriteSports.add("Hockey");
            favoriteSports.add("Table Tennis");
                        
            userDetails.setFavoriteSports(favoriteSports);
            //Create a new ObjectMapper, for mapping data to POJO
            ObjectMapper mapper = new ObjectMapper();
            //Set prettyprint option
            mapper.writerWithDefaultPrettyPrinter();
            //Write the userdetails data into test1.json
            mapper.writeValue(new File("c://Jackson//test1.json"), userDetails);
            System.out.println("JSON Write successful!!");
            
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
      • Create a new Object for the UserDetails class
UserDetails userDetails = new UserDetails();
      • Set value to the properties of UserDetails
userDetails.setName("Java");
userDetails.setAge(111);
List favoriteSports = new ArrayList();
favoriteSports.add("BaseBall");
favoriteSports.add("Hockey");
favoriteSports.add("Table Tennis");
userDetails.setFavoriteSports(favoriteSports);
      • 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 userDetails object into test1.json.
mapper.writeValue(new File("c://test1.json"), userDetails);

Output :

{"name":"Java","age":111,"favoriteSports":["BaseBall","Hockey","Table Tennis"]}

@JSONView Annotation

@JSONView is supported since Jackson 1.4, this will give the control of displaying the entities to the user.

First, we need to create our view class, it has three static classes NameOnly (For displaying name alone), AgeOnly (for displaying age alone), AgeAndFavSports (for displaying both Age and Favourite Sports)

package com.javainterviewpoint;

public class Views
{
    public static class NameOnly{};
    public static class AgeOnly{};
    public static class AgeAndFavSports extends AgeOnly {};
}

Now our POJO will be having the @JSONView annotation on it.

package com.javainterviewpoint;

import java.util.List;

import org.codehaus.jackson.map.annotate.JsonView;

public class UserDetails
{
    @JsonView(Views.NameOnly.class)
    private String name;
    @JsonView(Views.AgeOnly.class)
    private int age;
    @JsonView(Views.AgeAndFavSports.class)
    private List favoriteSports;
    
    public UserDetails()
    {
        super();
    }
    public UserDetails(String name, int age, List favoriteSports)
    {
        super();
        this.name = name;
        this.age = age;
        this.favoriteSports = favoriteSports;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    public List getFavoriteSports()
    {
        return favoriteSports;
    }
    public void setFavoriteSports(List favoriteSports)
    {
        this.favoriteSports = favoriteSports;
    }
}

@JSONView Example

package com.javainterviewpoint;

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

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

public class JSONView_Example
{
    public static void main(String[] args)
    {
        try
        {
            ObjectMapper mapper = new ObjectMapper();
            //By default all fields without explicit view definition are included, disable this
            mapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);

            UserDetails userDetails = new UserDetails();
            userDetails.setName("Java");
            userDetails.setAge(111);

            List favoriteSports = new ArrayList();
            favoriteSports.add("BaseBall");
            favoriteSports.add("Hockey");
            favoriteSports.add("Table Tennis");

            userDetails.setFavoriteSports(favoriteSports);

            String jsonString;
            //Displaying Name alone 
            jsonString = mapper.writerWithView(Views.NameOnly.class).writeValueAsString(userDetails);
            System.out.println("** Name Only View **");
            System.out.println(jsonString);
            //Displaying Age alone
            jsonString = mapper.writerWithView(Views.AgeOnly.class).writeValueAsString(userDetails);
            System.out.println("** Age Only View **");
            System.out.println(jsonString);
            //Displaying Both Age and FavouriteSports
            jsonString = mapper.writerWithView(Views.AgeAndFavSports.class).writeValueAsString(userDetails);
            System.out.println("** Age and FavouriteSports View **");
            System.out.println(jsonString);
            
        } catch (JsonGenerationException e)
        {
            e.printStackTrace();
        } catch (JsonMappingException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
       
    }
}

Output :
When we execute the JSONView_Example class, we will be getting the below output

** Name Only View **
{"name":"Java"}
** Age Only View **
{"age":111}
** Age and FavouriteSports View **
{"age":111,"favoriteSports":["BaseBall","Hockey","Table Tennis"]}

Filed Under: Core Java, Java Tagged With: @JSONView, Jackson JSON Example, ObjectMapper

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 ·