In this article, we will delve into the top methods for validating JSON strings in Java and provide comprehensive code examples for each method.
By the end of this post, you will have a thorough understanding of how to effectively validate JSON in java, ensuring the reliability and security of your code.
So, let’s explore these methods and elevate your Java programming skills to the next level.

1. Using org.json library

An effective way to validate JSON strings in Java is by using the org.json library.
This library provides a straightforward way to parse and validate JSON data.
Here’s an example of how you can utilize the org.json library for JSON validation:

import org.json.JSONObject;

public class JsonValidator {
   public static boolean validateJson(String json) {
      try {
        new JSONObject(json);
        return true;
      } catch (Exception e) {
        return false;
      }
   }
}

In this example, we are creating an object of JSONObject supplying it the json string.
If the json string is invalid, it will raise an error, which means that the json is invalid.

If the json string is an array, then JSONObject will not be able to parse it and consider it as an invalid json.

So, it will break for a string like

[{"name":"codippa", "type":"website"}]

To solve it, we need an extra check to test for JSON array as well, as shown below

import org.json.JSONObject;

public class JsonValidator {
  public static boolean validateJson(String json) {
    try {
      new JSONObject(json);
      return true;
    } catch (Exception e) {
      new JSONArray(json);
    }
  }
}

You can add this library to your project using below dependency.

<!-- MAVEN -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20231013</version>
</dependency>

// GRADLE
implementation 'org.json:json:20231013'

2. Google Gson

An alternative method for JSON validation is by integrating the Google Gson library.
This library provides a robust set of tools for parsing and validating JSON data in Java.
Here’s an example of how you can integrate Google Gson for JSON validation:

import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;

public class JsonValidator {
  public static boolean validateJson(String json) {
    try {
      JsonParser parser = new JsonParser();
      parser.parse(json);
      return true;
    } catch (JsonSyntaxException e) {
      return false;
    }
  }
}

Using Google Gson for JSON validation provides additional functionality and flexibility, making it a powerful tool for handling JSON data in Java.

Google Gson can be added to a project with below dependency as per the build tool.

<!-- XML -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

// GRADLE
implementation 'com.google.code.gson:gson:2.10.1'

3. Using Jackson ObjectMapper

Jackson library has an ObjectMapper class that is responsible for json related operations.

It has a readTree() method that accepts a json string as argument.

It throws JsonProcessingException and JsonMappingException, if the string is invalid json. Example,

ObjectMapper mapper = new ObjectMapper();
String s = "{\"name\":\"codippa\", \"type\":\"website\"}";
try {
  mapper.readTree(s);
} catch (JsonMappingException e) {
  e.printStackTrace();
} catch (JsonProcessingException e) {
  e.printStackTrace();
}

<!-- MAVEN -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.16.1</version>
</dependency>

// GRADLE
implementation 'com.fasterxml.jackson.core:jackson-databind:2.16.1'

Conclusion

By utilizing these validation techniques, you can effectively validate your JSON strings before processing.

Hope the article was useful.