Java
JSON validation
programming
string verification
software development

How to check whether a given string is valid JSON in Java

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

JSON (JavaScript Object Notation) is a widely used data format for data interchange in web applications. It is text-based, lightweight, and easy to understand. However, when working with JSON data in Java, one often needs to determine whether a given string is a valid JSON object or array. In this article, we will explore the process of checking JSON validity in Java with detailed explanations and examples.

Understanding JSON

Before diving into the validation process, it's important to understand what constitutes valid JSON. JSON data consists of key-value pairs enclosed in curly braces for objects and an ordered list of values enclosed in square brackets for arrays. A valid JSON might look like:

json
1{
2  "name": "Alice",
3  "age": 30,
4  "isStudent": false
5}

Or, as an array:

json
1[
2  "banana",
3  "apple",
4  "orange"
5]

A JSON string must maintain syntax accuracy—missing brackets, incorrect use of commas, and unmatched quotes are common reasons why JSON might be invalid.

Method to Check JSON Validity in Java

To validate a JSON string in Java, we typically use libraries, since Java's standard library does not provide built-in JSON parsers. Several popular libraries include:

  • org.json (often referred to as JSON-Java or json.org)
  • Jackson
  • Gson

Using org.json

The org.json package offers a simple way to validate JSON. The primary classes used for parsing and validation are JSONObject and JSONArray.

Example

java
1import org.json.JSONObject;
2import org.json.JSONArray;
3
4public class JSONValidator {
5    public static boolean isValidJSON(String jsonString) {
6        try {
7            new JSONObject(jsonString); // for JSON Objects
8        } catch (Exception e1) {
9            try {
10                new JSONArray(jsonString); // for JSON Arrays
11            } catch (Exception e2) {
12                return false; // neither a JSONObject nor a JSONArray
13            }
14        }
15        return true; // valid JSON
16    }
17
18    public static void main(String[] args) {
19        String json = "{\"name\":\"Alice\",\"age\":30,\"isStudent\":false}";
20        System.out.println("Is valid JSON: " + isValidJSON(json));
21
22        String invalidJson = "{name:Alice, age:30}";
23        System.out.println("Is valid JSON: " + isValidJSON(invalidJson));
24    }
25}

Using Jackson

Jackson is another powerful library that can handle JSON parsing and validation.

Example

java
1import com.fasterxml.jackson.databind.ObjectMapper;
2
3public class JSONValidator {
4    public static boolean isValidJSON(String jsonString) {
5        try {
6            ObjectMapper objectMapper = new ObjectMapper();
7            objectMapper.readTree(jsonString);
8            return true;
9        } catch (Exception e) {
10            return false; // JSON is invalid
11        }
12    }
13
14    public static void main(String[] args) {
15        String json = "{\"name\":\"Alice\",\"age\":30,\"isStudent\":false}";
16        System.out.println("Is valid JSON: " + isValidJSON(json));
17
18        String invalidJson = "{name:Alice, age:30}";
19        System.out.println("Is valid JSON: " + isValidJSON(invalidJson));
20    }
21}

Using Gson

Gson is a library developed by Google for JSON parsing, which also provides simple validation essentials.

Example

java
1import com.google.gson.JsonParser;
2
3public class JSONValidator {
4    public static boolean isValidJSON(String jsonString) {
5        try {
6            JsonParser.parseString(jsonString);
7            return true;
8        } catch (Exception e) {
9            return false; // JSON is invalid
10        }
11    }
12
13    public static void main(String[] args) {
14        String json = "{\"name\":\"Alice\",\"age\":30,\"isStudent\":false}";
15        System.out.println("Is valid JSON: " + isValidJSON(json));
16
17        String invalidJson = "{name:Alice, age:30}";
18        System.out.println("Is valid JSON: " + isValidJSON(invalidJson));
19    }
20}

Comparison of Libraries

LibraryEase of UsePerformanceAdditional Features
org.jsonEasyModerateLightweight but limited in configuration options and error details.
JacksonModerateHighHigh-performance with a wealth of features, extensive configuration options.
GsonEasyHighFlexible, good for deserialization and POJOs but slower for large JSON.

Conclusion

Choosing the right library depends on the needs of your application. If simple validation suffices, org.json or Gson can do a great job with minimal setup. However, for more complex JSON processing, including transformations and performance optimizations, Jackson is the preferred choice.

By understanding the pros and cons of each library, developers can effectively validate JSON strings in their Java applications, ensuring data integrity and smooth application functionalities.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.