Open In App

Java Program to Implement a JSON Parser

Last Updated : 30 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

JSON is commonly used in order to exchange data to and back fro from a  web server. The key point here is when we are getting the data from the webserver then it is returned always as a string so do we need t take care in our java program. 

Illustration:

{"Geeks", "NIT", "Male", "30"}

This data is returned by JSON parser as a JavaScript object so do it becomes as follows:

const object = JSON.parse({"Geeks", "NIT", "Male", "30"}) ;

So do the same dealing is computed with arrays while JSON s parsing data. Let us write a java program invoking methods to make it simpler to grasp how JSON parser is implemented.

Example

Java




// Java Program to Implement JSON Parser
 
// Importing required classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
 
// Defining constants for json parsers
enum CONSTANTS {
 
    CURLY_OPEN_BRACKETS('{'),
    CURLY_CLOSE_BRACKETS('}'),
    SQUARE_OPEN_BRACKETS('['),
    SQUARE_CLOSE_BRACKETS(']'),
    COLON(':'),
    COMMA(','),
    SPECIAL('|');
 
    private final char constant;
 
    // Constructor
    CONSTANTS(char constant) { this.constant = constant; }
 
    // Method
    // Overriding exiting toString() method
    @Override public String toString()
    {
        return String.valueOf(constant);
    }
}
 
// Class 1
// To parse json object
class JSONObject {
 
    private final static char specialChar;
    private final static char commaChar;
    private HashMap<String, String> objects;
 
    static
    {
        specialChar = String.valueOf(CONSTANTS.SPECIAL)
                          .toCharArray()[0];
        commaChar = String.valueOf(CONSTANTS.COMMA)
                        .toCharArray()[0];
    }
 
    // Constructor if this class
    public JSONObject(String arg) { getJSONObjects(arg); }
 
    // Method 1
    // Storing json objects as key value pair in hash map
    public void getJSONObjects(String arg)
    {
 
        objects = new HashMap<String, String>();
 
        if (arg.startsWith(String.valueOf(
                CONSTANTS.CURLY_OPEN_BRACKETS))
            && arg.endsWith(String.valueOf(
                CONSTANTS.CURLY_CLOSE_BRACKETS))) {
 
            StringBuilder builder = new StringBuilder(arg);
            builder.deleteCharAt(0);
            builder.deleteCharAt(builder.length() - 1);
            builder = replaceCOMMA(builder);
 
            for (String objects : builder.toString().split(
                     String.valueOf(CONSTANTS.COMMA))) {
 
                String[] objectValue = objects.split(
                    String.valueOf(CONSTANTS.COLON), 2);
 
                if (objectValue.length == 2)
                    this.objects.put(
                        objectValue[0]
                            .replace("'", "")
                            .replace("\"", ""),
                        objectValue[1]
                            .replace("'", "")
                            .replace("\"", ""));
            }
        }
    }
 
    // Method 2
    public StringBuilder replaceCOMMA(StringBuilder arg)
    {
 
        boolean isJsonArray = false;
 
        for (int i = 0; i < arg.length(); i++) {
            char a = arg.charAt(i);
 
            if (isJsonArray) {
 
                if (String.valueOf(a).compareTo(
                        String.valueOf(CONSTANTS.COMMA))
                    == 0) {
                    arg.setCharAt(i, specialChar);
                }
            }
 
            if (String.valueOf(a).compareTo(String.valueOf(
                    CONSTANTS.SQUARE_OPEN_BRACKETS))
                == 0)
                isJsonArray = true;
            if (String.valueOf(a).compareTo(String.valueOf(
                    CONSTANTS.SQUARE_CLOSE_BRACKETS))
                == 0)
                isJsonArray = false;
        }
 
        return arg;
    }
 
    // Method 3
    // Getting json object value by key from hash map
    public String getValue(String key)
    {
        if (objects != null) {
            return objects.get(key).replace(specialChar,
                                            commaChar);
        }
        return null;
    }
 
    // Method 4
    // Getting json array by key from hash map
    public JSONArray getJSONArray(String key)
    {
        if (objects != null)
            return new JSONArray(
                objects.get(key).replace('|', ','));
        return null;
    }
}
 
// Class 2
// To parse json array
class JSONArray {
 
    private final static char specialChar;
    private final static char commaChar;
 
    private ArrayList<String> objects;
 
    static
    {
        specialChar = String.valueOf(CONSTANTS.SPECIAL)
                          .toCharArray()[0];
        commaChar = String.valueOf(CONSTANTS.COMMA)
                        .toCharArray()[0];
    }
 
    // Constructor of this class
    public JSONArray(String arg) { getJSONObjects(arg); }
 
    // Method 1
    // Storing json objects in array list
    public void getJSONObjects(String arg)
    {
 
        objects = new ArrayList<String>();
 
        if (arg.startsWith(String.valueOf(
                CONSTANTS.SQUARE_OPEN_BRACKETS))
            && arg.endsWith(String.valueOf(
                CONSTANTS.SQUARE_CLOSE_BRACKETS))) {
 
            StringBuilder builder = new StringBuilder(arg);
 
            builder.deleteCharAt(0);
            builder.deleteCharAt(builder.length() - 1);
 
            builder = replaceCOMMA(builder);
 
            // Adding all elements
            // using addAll() method of Collections class
            Collections.addAll(
                objects,
                builder.toString().split(
                    String.valueOf(CONSTANTS.COMMA)));
        }
    }
 
    // Method 2
    public StringBuilder replaceCOMMA(StringBuilder arg)
    {
        boolean isArray = false;
 
        for (int i = 0; i < arg.length(); i++) {
            char a = arg.charAt(i);
            if (isArray) {
 
                if (String.valueOf(a).compareTo(
                        String.valueOf(CONSTANTS.COMMA))
                    == 0) {
                    arg.setCharAt(i, specialChar);
                }
            }
 
            if (String.valueOf(a).compareTo(String.valueOf(
                    CONSTANTS.CURLY_OPEN_BRACKETS))
                == 0)
                isArray = true;
 
            if (String.valueOf(a).compareTo(String.valueOf(
                    CONSTANTS.CURLY_CLOSE_BRACKETS))
                == 0)
                isArray = false;
        }
 
        return arg;
    }
 
    // Method  3
    // Getting json object by index from array list
    public String getObject(int index)
    {
        if (objects != null) {
            return objects.get(index).replace(specialChar,
                                              commaChar);
        }
 
        return null;
    }
 
    // Method 4
    // Getting json object from array list
    public JSONObject getJSONObject(int index)
    {
 
        if (objects != null) {
            return new JSONObject(
                objects.get(index).replace('|', ','));
        }
 
        return null;
    }
}
 
// Class 3
// To parse json string
public class Parser {
 
    // json string with user data
    // Custom data been passed as in arguments
    private final static String jsonString
        = "{'name':'user','id':1234,'marks':[{'english':85,'physics':80,'chemistry':75}]}";
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Parse json object for user data
        JSONObject user = new JSONObject(jsonString);
 
        // Get json array for user's marks
        JSONArray marks = user.getJSONArray("marks");
 
        // Get json object for subject's marks
        JSONObject subjects = marks.getJSONObject(0);
 
        // Print and display commands
        System.out.println(
            String.format("English marks - %s",
                          subjects.getValue("english")));
        System.out.println(
            String.format("Physics marks - %s",
                          subjects.getValue("physics")));
        System.out.println(
            String.format("Chemistry marks - %s",
                          subjects.getValue("chemistry")));
    }
}


Output

English marks - 85
Physics marks - 80
Chemistry marks - 75

 



Similar Reads

Difference Between SAX Parser and DOM Parser in Java
There are two types of XML parsers namely Simple API for XML and Document Object Model. SAXDOMSAX (Simple API for XML), is the most widely adopted API for XML in Java and is considered the de-facto standard. Although it started as a library exclusive to Java, it is now a well-known API distributed over a variety of programming languages. It is an o
4 min read
Java Program to Convert JSON String to JSON Object
Gson is a Java library that can be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects whose source code we don't have. It provides the support to transfer data in between different programming languages modules. JSON String Representation: The string must be in JSON f
2 min read
Java JSON Processing (JSON-P) with Example
JSON (JavaScript Object Notation) is text-based lightweight technology. Nowadays it is a dominant and much-expected way of communication in the form of key-value pairs. It is an easier way of transmitting data as it is having nice formatted way. We can nest the objects and also can provide JSON arrays also. Implementation steps for a maven project
7 min read
What is JSON-Java (org.json)?
JSON(Javascript Object Notation) is a lightweight format of data exchange and it is independent of language. It is easily read and interpreted by humans and machines. Hence nowadays, everywhere JSON is getting used for transmitting data. Let us see how to prepare JSON data by using JSON.org JSON API in java JSON.simple is a library in java is used
5 min read
StAX vs SAX Parser in Java
Streaming the API for XML, called the StAX, is an API for reading and writing the XML Documents. It was introduced in Java 6 and is considered superior to SAX and DOM which are other methods in Java to access XML. Java provides several ways [APIs] to access XML. Traditionally, XML APIs are either- Tree-based [such as StAX, DOM]: The entire document
3 min read
DefaultHandler in SAX Parser in Java
SAX is nothing but a Simple API for XML and it is an event-based parser for XML documents. It differs from a DOM parser in such a way that a parse tree is not created by a SAX parser. The process is done in a sequential order starting at the top of the document and ending with the closing of the ROOT element. Timely notifications are also being sen
4 min read
StAX XML Parser in Java
This article focuses on how one can parse a XML file in Java.XML : XML stands for eXtensible Markup Language. It was designed to store and transport data. It was designed to be both human- and machine-readable. That’s why, the design goals of XML emphasize simplicity, generality, and usability across the Internet. Why StAX instead of SAX ? SAX: The
6 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more. Approach: We are going to fetch JSON data from one of free website,
2 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
Practice Tags :