How to Check if String is Valid JSON in Java and JavaScript

5 min read
Updated: Dec 16, 2020

JSON is a simple data interchange format used heavily for exchanging data between web applications over the internet. When you are working in Java, you encounter many use cases where you receive data in the form of strings. These strings are typically structured as per the JSON specifications and contain numbers, strings, objects, arrays, or boolean values.

But before you can use the values contained in the string as JSON, you need to check if the string is a valid JSON object. And to do so, there are a few ways in Java that can be used to easily validate if the string is valid JSON.

Using Package org.json

Using the package org.json, this package is the reference implementation of JSON specifications as a java package.

To check the valid JSON, the very first step is to try parsing the string and recording exceptions. In your java program, you need to import the org.json package, and then you can create a function that takes a string as input and returns true if the string is valid JSON else returns false.

Additionally, you can also check if the string is a valid Array in the form of a JSON object. Given below is the code of the function that tells if JSON is valid or not in Java-

import org.json.*;

public boolean isStringValidJson(String str) {
    try {
        new JSONObject(str);
        // the above java function converts string to json else returns false 
    } catch (JSONException exp) {
        try {
            new JSONArray(str);
        // the above function returns valid JSON array else returns false
        // Use this only if you want to check if string is a valid array         too
        } catch (JSONException exp) {
            return false;
        }
    }
    return true;
}

Use Jackson Library to validate the String

Another method to validate if string is a properly formatted JSON is availalbe in the Jackson library. Jackson is very popular and also known as the best library to parse and generate JSON in Java.

To use this library in your code, first of all add it to the project path. If you are using maven, then simply add below dependency in the configuration.

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

With the above dependency added, all you need is to implement the below code. This is similar to the way we implemented function to check valid JSON string using JSON.ORG package.

The below function isStringValidJson also returns true if string is valid json else returns false. Additionally, it maps the the data in mapper variable that you can use further.

import com.fasterxml.jackson.databind.ObjectMapper;

public final class checkMyString {
  private checkMyString(){}

  public static boolean isStringValidJson(String str ) {
    try {
       final ObjectMapper mapper = new ObjectMapper();
       mapper.readTree(str);
       return true;
    } catch (IOException e) {
       return false;
    }
  }
}

Using GSON Library from Google

This is another method you can try out to check the JSON that is valid or not. GSON is one of the oldest Java library used by developers to convert JSON string to java objects and also to turn java objects into JSON format.

Again, to start with, you need to add the dependency. If you are using Gradle, you can add dependency as below –

dependencies {
  implementation 'com.google.code.gson:gson:2.9.0'
}

If you are using maven, then add the dependency as below –

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

After adding the dependencies, you can implement the below code to check validity of string as JSON. Simply create a stringUtils class and add string validation utility function in that.

The function implemented below to check the string is isStringValidJson and takes string as input parameter. In the function it calls, fromJson function availalbe in the gson library. If the string is actually a valid JSON, then this utility function returns true, else false.

import com.google.gson.Gson;

public final class stringUtils {
  private static final Gson gson = new Gson();

  private stringUtils(){}

  public static boolean isStringValidJson(String str) {
      try {
          gson.fromJson(str, Object.class);
          return true;
      } catch(com.google.gson.JsonSyntaxException exp) { 
          return false;
      }
  }
}

Check whether the string is JSON Javascript.

You can also check whether the string is JSON or not in Javascript. To do so, we can use JSON.parse method in Javascript. This method parses the provided string and creates corresponding JavaScript object or value as described by the string.

Givne below is a simple JavaScript function to check if JSON valid or not –

function isStringValidJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

JSON.parse does a lot of calculations to parse the string to give you final JSON objects if successful. But since you just want to check if string is valid or not, you can simple return true if parsing is successful else false, like in above function.

Conclusion

There are multiple methods availalbe to check if string is valid json in java as well as in javascript. Some methods may not work well depending on complexity of the JSON contained in the string. You should try out all these methods to figure out what works best for you.

You will see that sometimes, trailing commas cause issues, or extra white spaces needs to be removed etc. But there are ways to sort out those minor issues, and also a little bit of hit and trial becomes necessary at times.

You may also like to read: Yaml vs JSON comparison

Tags

Sophia Rodreguaze

@noeticsophia

Sophia is the contributing editor at noeticforce.com. She writes about anything and everything related to technology.

More from Noeticforce
Join noeticforce

Create your free account to customize your reading & writing experience

Ⓒ 2021 noeticforce — All rights reserved