How to parse JSON in Java

Because it is easy to read and understand, JSON (JavaScript Object Notation) has become a widely used data format for system-to-system communication. JSON data parsing is a frequent operation in many Java applications, such as data processing pipelines and web services. This thorough tutorial will cover various methods and Java libraries for parsing JSON, giving you the skills and resources to manage JSON data in Java applications.

Understanding JSON

The lightweight, text-based, language-independent JSON (JavaScript Object Notation) data interchange format is simple for computers and people to read and write. Arrays and objects are the two structured kinds that JSON may represent. An unordered collection of one or more name-value pairs is referred to as an object. An ordered list of zero or more values is called an array. Strings, integers, booleans, null, and these two structured kinds can all be used as values.

A basic Wikipedia example illustrates how an object that defines a person might be represented in JSON. The object has an array value of phone number objects, an object value that represents the person’s address, a numeric value for age, and string values for the first and last names.

{

    "firstName": "Enable",

    "lastName": "Geek",

    "address": {

        "streetAddress": "21 2nd Street",

        "city": "New York",

        "state": "NY",

        "postalCode": 10021

    },

    "phoneNumbers": [

        {

            "type": "home",

            "number": "212 555-1234"

        },

        {

            "type": "fax",

            "number": "646 555-4567" 

        }

    ] 

}


Manual Parsing

Using the org.json package, which offers classes like JSONObject and JSONArray to parse JSON strings manually, is the most straightforward method of parsing JSON in Java.

import org.json.*;

public class ManualJsonParsing {

    public static void main(String[] args) {

        String jsonString = "{\"name\": \"Amit\", \"age\": 21}";

        JSONObject jsonObject = new JSONObject(jsonString);

        String name = jsonObject.getString("name");

        int age = jsonObject.getInt("age");

        System.out.println("Name: " + name + ", Age: " + age);

    }

}


Although this method is simple, it may become laborious and prone to mistakes, particularly when dealing with intricate JSON structures.

Gson Library

Java objects may be translated from Java to their JSON form and back again using the Gson package. It offers a straightforward and adaptable API for processing JSON data.

Setup:

You must add the Gson library to your project dependencies to utilize Gson in your Java project. To accomplish this, update your pom.xml file with the following Maven dependency:

<dependency>

    <groupId>com.google.code.gson</groupId>

    <artifactId>gson</artifactId>

    <version>2.8.8</version>

</dependency>


Alternatively, add the following dependency to your build.gradle file if you’re using Gradle:

implementation ‘com.google.code.gson:gson:2.8.8’

ObjectMapper Basics

To read and write JSON data, Jackson offers an ObjectMapper class. To convert Java objects from JSON strings and vice versa, you may create an instance of ObjectMapper and utilize its methods.

JSON Parsing to Java Objects

Jackson’s readValue() function lets you parse JSON texts straight into Java objects. As an illustration, consider this:

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JacksonParsing {

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

        String jsonString = "{\"name\": \"Amit\", \"age\": 21}";

        ObjectMapper objectMapper = new ObjectMapper();

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

        System.out.println("Name: " + person.getName() + ", Age: " + person.getAge());

    }

}


This will output:

Name: Amit, Age: 21

Advanced Functionalities

Jackson offers several sophisticated capabilities, including custom deserialization, tree model support, and streaming API support. You may effectively manage intricate JSON parsing circumstances with the help of these capabilities.

JSON-P Library

A Java API called JSON-P (JSON Processing) handles JSON data. It offers the Streaming API and Object Model API as two programming paradigms for JSON processing.

Configuration:

If you’re using a Java EE application server, JSON-P is part of the platform and doesn’t require any further configuration. In your project dependencies, you must include the JSON-P library if you are using a standalone Java SE application. To accomplish this, update your pom.xml file with the following Maven dependency:

<dependency>

    <groupId>javax.json</groupId>

    <artifactId>javax.json-api</artifactId>

    <version>1.1.4</version>

</dependency>

<dependency>

    <groupId>org.glassfish</groupId>

    <artifactId>javax.json</artifactId>

    <version>1.1.4</version>

</dependency>


Alternatively, add the following dependencies to your build.gradle file if you’re using Gradle:

implementation ‘javax.json:javax.json-api:1.1.4’

implementation ‘org.glassfish:javax.json:1.1.4’

Basics of JSON Processing (JSON-P) API

For JSON processing, JSON-P offers two primary programming models: Streaming API and Object Model API.

API for streaming

For big JSON documents that won’t fit in memory, the Streaming API lets you handle JSON data in a streaming fashion. This illustrates how to parse JSON using the Streaming API:

import javax.json.Json;

import javax.json.stream.JsonParser;

import java.io.StringReader;

public class JsonpStreamingApi {

    public static void main(String[] args) {

        String jsonString = "{\"name\": \"Amit\", \"age\": 21}";

        JsonParser parser = Json.createParser(new StringReader(jsonString));

        while (parser.hasNext()) {

            JsonParser.Event event = parser.next();

            if (event == JsonParser.Event.KEY_NAME) {

                String key = parser.getString();

                parser.next();

                String value = parser.getString();

                System.out.println(key + ": " + value);

            }

        }

    }

}



This will output:

name: Amit

age: 21

Object Model API

You may represent JSON data as a tree structure of JsonObject and JsonArray objects using the Object Model API. This illustrates how to read JSON using the Object Model API:

import javax.json.Json;

import javax.json.JsonObject;

public class JsonpObjectModelApi {

    public static void main(String[] args) {

        String jsonString = "{\"name\": \"Amit\", \"age\": 21}";

        JsonObject jsonObject = Json.createReader(new StringReader(jsonString)).readObject();

        String name = jsonObject.getString("name");

        int age = jsonObject.getInt("age");

        System.out.println("Name: " + name + ", Age: " + age);

    }

}


Best Practices

There are a few best practices to adhere to while parsing JSON in Java to guarantee effective and maintainable code:

  • Instead of parsing JSON by yourself, use a parser library like Gson, Jackson, or JSON-P.
  • Consider the parsing library’s memory and performance requirements, particularly for big JSON documents.
  • Treat edge circumstances and failures compassionately, such as missing fields or improper JSON syntax.
  • To make code easier to understand and maintain, give variables meaningful names and comments.
  • Test your JSON parsing code extensively with various JSON data types and edge situations.

Scalable applications in Java development require efficient and accurate JSON data parsing. Various methodologies and libraries offer advantages and considerations, including Gson, Jackson, and JSON-P. Manual parsing can become error-prone, while Gson and Jackson provide elegant solutions. JSON-P, part of the Java EE platform, offers a standard API for JSON processing.

When choosing a JSON parsing methodology, consider factors like performance, ease of use, flexibility, and maintenance. Performance benchmarks can guide decision-making, while ease of use and flexibility can be assessed through documentation and community support. Flexibility can be enhanced by custom serialization and compatibility with Java features. Library stability and active development ensure ongoing support.

In conclusion, your unique project needs, development goals, and preferences will ultimately determine which Java JSON parsing technology you choose. You may make well-informed judgments and put into place reliable JSON parsing solutions that satisfy the requirements of your Java applications both today and in the future by utilizing the insights and suggestions provided in this book. To keep your JSON parsing techniques current and efficient, don’t forget to keep up with changes and improvements in the Java environment.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.