Check if string is valid json

In this article, we will explore 3 different ways to check if a json string is a valid json in java with examples.
Methods covered will be

Method 1: Using JSONObject
org.json library is a very simple and lightweight library for dealing with json string and objects in java.
It provides a JSONObject class which converts a json string to a json object using its constructor.

JSONObject throws a JSONException, if it cannot parse the supplied json string.
Its documentation states,

JSONException if the parse fails or doesn’t yield a JSONObject

So, successful creation of JSONObject means that the json string is valid.

If it fails, means the json string is not a valid json. Example,

String jsonStrOne = "{ \"name\" : "\ABC\" }";
String jsonStrOne = "ABC";
try {
  JSONObject jsonObjOne = new JSONObject(jsonStrOne);
  System.out.print("Valid Json");
  JSONObject jsonObjTwo = new JSONObject(jsonStrTwo);
  System.out.print("Valid Json");
} catch(JSONException e) {
  System.out.print("Invalid Json");
}

Note that we enclosed the creation of JSONObject in a try-catch block.
An exception means that there is some problem with parsing and the json string is not valid.
This prints

Valid Json
Invalid Json

There is a problem with above approach.
If we supply a valid json string which contains a json array, then also JSONObject will fail, as it considers it as an invalid json.

There is a separate class JSONArray in this library for handling json array.
So, at the first failure, we need to check, if the supplied string is a json array as shown below.

String jsonStr = "[{ \"name\" : "\ABC\" }, { \"name\" : "\DEF\" }]"
try {
  JSONObject jsonObj = new JSONObject(jsonStr);
  System.out.print("Valid Json");
} catch(JSONException e) {
  try {
    // try parsing as json array
    JSONArray jArray = new JSONArray(jsonStr);
  } catch(JSONException e1) {
      System.out.print("Invalid Json");
  }
}

Below are the dependencies for this library

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

// MAVEN
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20220320</version>
</dependency>

Method 2: Using Jackson ObjectMapper
Jackson is another very popular library for parsing a json string to json object.
It has an ObjectMapper class which can easily create a json object from a json string and vice-versa.

ObjectMapper has a readTree() method which accepts a json string argument and returns a json object as JsonNode, if it is able to parse it successfully.

readTree() throws a JsonProcessingException, if there is some error in parsing. Example,

String jsonStr = "ABC";
ObjectMapper mapper = new ObjectMapper();
try {
  mapper.readTree(jsonStr);
  System.out.print("Valid Json");
} catch (JsonMappingException e) {
    e.printStackTrace();
} catch (JsonProcessingException e) {
    System.out.print("Invalid Json");
}

Below is the dependency for Jackson

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

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

Method 3: Using Gson
Google gson is another java library for parsing of json string to json objects.
It has JsonParser class having a parseString() method which takes a json string argument and returns a JsonElement object for interacting with it.

parseString() throws JsonSyntaxException if there is any error in parsing.

In order to determine if a json string is valid, enclose this method between a try-catch block as shown below

String s = "{\"name\":\"Abc\"}";
try {
  JsonParser.parseString(s);
 System.out.print("Valid Json");
} catch (JsonSyntaxException e) {
 System.out.print("Invalid Json");
}

Following is the dependency for gson

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

// MAVEN
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.9.0</version>
</dependency>

In this article, we looked at 3 different ways to check if a json string is valid json.
All the methods are reliable and easy to use. Which method you want to use, depends on the project and requirements.
Hope the article was useful.