Skip to main content

How to Parse JSON to/from Java Object using Jackson Example

How to Parse JSON to/from Java Object using Jackson Example

In this example You will learn how to parse a  JSON String to Java and  how to convert Java Object to JSON format using Jackson. JSON stands for JavaScript Object notation is a subset of JavaScript object syntax, which allows all JavaScript client to process it without using any external library. Because of its compact size, compared to XML and platform independence nature makes JSON a favorite format for transferring data via HTTP. Though Java doesn't have any inbuilt support to parse JSON response in core library, Java developers are lucky to have couple of good and feature rich JSON processing libraries such as GSONJackson and JSON-simple.  Jackson in a high performance, one of the fasted JSON parsing library, which also provides streaming capability. It has no extenal dependency and solely depends on JDK. It is also powerful and provides full binding support for common JDK classes as well as any Java Bean class, e.g. Player in our case. It also provides data binding for Java Collection classes e.g. Map as well Enum.


Jackson Library

The complete Jackson library consists of 6 jar files that are used for many diffident operation. In this example we are going to need just one, mapper-asl.jar. If you want to install the full library to your project you can download and use jackson-all-*.jar that includes all the jars. You can download them from the Jackson Download Page. Alternatively, If your using Maven in your project (which you should) then you can add following dependency in your pom.xml.

<dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-all</artifactId>
      <version>1.9.11</version>
</dependency>


You need Default Constructor in Your Bean Class

When I first run my program, I get following exception because  I had parametric constructor inPlayer class and not bothered to add a  no-argument default constructor :

org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class Player]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: player.json; line: 1, column: 2]
               at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
               at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObjectUsingNonDefault(BeanDeserializer.java:746)
               at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:683)
               at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
               at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
               at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1817)
               at JSONParser.toJava(Testing.java:30)
               at JSONParser.main(Testing.java:17)

Once I added the default constructor on Player class this error is gone. Probably this is another reason why you should have a default or no-arg constructor in Java class.


How to parse JSON in Java

Here is our sample program to parse JSON String in Java. As I said, in this example we will use Jackson, an open source JSON parsing library with rich features. There are two static methods here, toJSON() which converts a Java instance to JSON and fromJSON() method which reads a JSON file, parse it and create Java objects. They key object here is ObjectMapper class from Jackson library, which used for converting JSON to Java and vice-versa.

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

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

/**
 * Java Program to parse JSON String to Java object and converting a Java object to equivalent
 * JSON String.
 *
 * @author Javin Paul
 */
public class JSONParser {

    public static void main(String args[]) {
        toJSON();  // converting Java object to JSON String
        toJava();  // parsing JSON file to create Java object
    }

    /**
     * Method to parse JSON String into Java Object using Jackson Parser.
     *
     */
    public static void toJava() {
       
        // this is the key object to convert JSON to Java
        ObjectMapper mapper = new ObjectMapper();

        try {
            File json = new File("player.json");
            Player cricketer = mapper.readValue(json, Player.class);
            System.out.println("Java object created from JSON String :");
            System.out.println(cricketer);

        } catch (JsonGenerationException ex) {
            ex.printStackTrace();
        } catch (JsonMappingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();

        }
    }

    /**
     * Java method to convert Java Object into JSON String with help of Jackson API.
     *
     */
    public static void toJSON() {
        Player kevin = new Player("Kevin", "Cricket", 32, 221, new int[]{33, 66, 78, 21, 9, 200});

        // our bridge from Java to JSON and vice versa
        ObjectMapper mapper = new ObjectMapper();

        try {
            File json = new File("player.json");
            mapper.writeValue(json, kevin);
            System.out.println("Java object converted to JSON String, written to file");
            System.out.println(mapper.writeValueAsString(kevin));

        } catch (JsonGenerationException ex) {
            ex.printStackTrace();
        } catch (JsonMappingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();

        }
    }

}

/*
 * A simple Java values class with getters and setters. We will convert Player class instance into
 * JSON String and a JSON object to Player instance.
 */
class Player {

    private String name;
    private String sport;
    private int age;
    private int id;
    private int[] lastScores;

    public Player() {
        //just there, need by Jackson library
    }

    public Player(String name, String sport, int age, int id, int[] lastinnings) {
        this.name = name;
        this.sport = sport;
        this.age = age;
        this.id = id;
        lastScores = lastinnings;
    }

    public final String getName() {
        return name;
    }

    public final String getSport() {
        return sport;
    }

    public final int getAge() {
        return age;
    }

    public final int getId() {
        return id;
    }

    public final int[] getLastScores() {
        return lastScores;
    }

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

    public final void setSport(String sport) {
        this.sport = sport;
    }

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

    public final void setId(int id) {
        this.id = id;
    }

    public final void setLastScores(int[] lastScores) {
        this.lastScores = lastScores;
    }

    @Override
    public String toString() {
        return "Player [name=" + name + ", sport=" + sport + ", age=" + age + ", id=" + id
                + ", recent scores=" + Arrays.toString(lastScores) + "]";
    }

}


Output:
Java object converted to JSON String, written to file
{"name":"Kevin","sport":"Cricket","age":32,"id":221,"lastScores":[33,66,78,21,9,200]}
Java object created from JSON String :
Player [name=Kevin, sport=Cricket, age=32, id=221, recent scores=[33, 66, 78, 21, 9, 200]]


This will also create file called player.json in your current or project directory.


That's all about how to parse JSON String in Java and convert a Java object to JSON using Jackson API. Though there are couple of more good open source library available for JSON parsing and conversion e.g. GSON and JSON-Simple but Jackson is one of the best and feature rich, its also tried and tested library in many places, means you should be little worried about any nasty bug while parsing your big JSON String.

If you like this tutorial and want to know more about how to work with JSON and Java, check out following fantastic articles :
  • How to read JSON String from File in Java (solution)
  • How to parse JSON Array to Java array? (solution)
  • How to convert JSON to Java Object? (example)

Comments

Popular posts from this blog

sxhkd volume andbrightness config for dwm on void

xbps-install  sxhkd ------------ mkdir .config/sxhkd cd .config/sxhkd nano/vim sxhkdrc -------------------------------- XF86AudioRaiseVolume         amixer -c 1 -- sset Master 2db+ XF86AudioLowerVolume         amixer -c 1 -- sset Master 2db- XF86AudioMute         amixer -c 1 -- sset Master toggle alt + shift + Escape         pkill -USR1 -x sxhkd XF86MonBrightnessUp          xbacklight -inc 20 XF86MonBrightnessDown          xbacklight -dec 20 ------------------------------------------------------------- amixer -c card_no -- sset Interface volume run alsamixer to find card no and interface names xbps-install -S git git clone https://git.suckless.org/dwm xbps-install -S base-devel libX11-devel libXft-devel libXinerama-devel  vim config.mk # FREETYPEINC = ${X11INC}/freetype2 #comment for non-bsd make clean install   cp config.def.h config.h vim config.h xbps-install -S font-symbola #for emoji on statusbar support     void audio config xbps-i

Hidden Wiki

Welcome to The Hidden Wiki New hidden wiki url 2015 http://zqktlwi4fecvo6ri.onion Add it to bookmarks and spread it!!! Editor's picks Bored? Pick a random page from the article index and replace one of these slots with it. The Matrix - Very nice to read. How to Exit the Matrix - Learn how to Protect yourself and your rights, online and off. Verifying PGP signatures - A short and simple how-to guide. In Praise Of Hawala - Anonymous informal value transfer system. Volunteer Here are five different things that you can help us out with. Plunder other hidden service lists for links and place them here! File the SnapBBSIndex links wherever they go. Set external links to HTTPS where available, good certificate, and same content. Care to start recording onionland's history? Check out Onionland's Museum Perform Dead Services Duties. Introduction Points Ahmia.fi - Clearnet search engine for Tor Hidden Services (allows you

download office 2021 and activate

get office from here  https://tb.rg-adguard.net/public.php open powershell as admin (win+x and a ) type cmd  goto insall dir 1.         cd /d %ProgramFiles(x86)%\Microsoft Office\Office16 2.           cd /d %ProgramFiles%\Microsoft Office\Office16 try 1 or 2 depending on installation  install volume license  for /f %x in ('dir /b ..\root\Licenses16\ProPlus2021VL_KMS*.xrm-ms') do cscript ospp.vbs /inslic:"..\root\Licenses16\%x" activate using kms cscript ospp.vbs /setprt:1688 cscript ospp.vbs /unpkey:6F7TH >nul cscript ospp.vbs /inpkey:FXYTK-NJJ8C-GB6DW-3DYQT-6F7TH cscript ospp.vbs /sethst:s8.uk.to cscript ospp.vbs /act Automatic script (windefender may block it) ------------------------------------------------------------------------------------------------------------------- @echo off title Activate Microsoft Office 2021 (ALL versions) for FREE - MSGuides.com&cls&echo =====================================================================================&