Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you check given string is JSON or not?

parse(false) or JSON. parse(null) all will return true. If you test a . srt file (subtitle file) with this function, it will give true.

How do I check if data is valid in JSON?

Usage: isJSON({}) will be false , isJSON('{}') will be true . To check if something is an Array or Object (parsed JSON): // vanillaJS function isAO(val) { return val instanceof Array || val instanceof Object ?

Is a string a valid JSON object?

JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON. Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.

How do I check if a string is JSONObject or JSONArray?

JSONArray interventions; if(intervention == null) interventions=jsonObject. optJSONArray("intervention"); This will return you an array if it's a valid JSONArray or else it will give null .


A wild idea, try parsing it and catch the exception:

import org.json.*;

public boolean isJSONValid(String test) {
    try {
        new JSONObject(test);
    } catch (JSONException ex) {
        // edited, to include @Arthur's comment
        // e.g. in case JSONArray is valid as well...
        try {
            new JSONArray(test);
        } catch (JSONException ex1) {
            return false;
        }
    }
    return true;
}

This code uses org.json JSON API implementation that is available on github, in maven and partially on Android.


JACKSON Library

One option would be to use Jackson library. First import the latest version (now is):

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

Then, you can implement the correct answer as follows:

import com.fasterxml.jackson.databind.ObjectMapper;

public final class JSONUtils {
  private JSONUtils(){}

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

Google GSON option

Another option is to use Google Gson. Import the dependency:

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

Again, you can implement the proposed solution as:

import com.google.gson.Gson;

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

  private JSONUtils(){}

  public static boolean isJSONValid(String jsonInString) {
      try {
          gson.fromJson(jsonInString, Object.class);
          return true;
      } catch(com.google.gson.JsonSyntaxException ex) { 
          return false;
      }
  }
}

A simple test follows here:

//A valid JSON String to parse.
String validJsonString = "{ \"developers\": [{ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
        "{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";

// Invalid String with a missing parenthesis at the beginning.
String invalidJsonString = "\"developers\": [ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
        "{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";

boolean firstStringValid = JSONUtils.isJSONValid(validJsonString); //true
boolean secondStringValid = JSONUtils.isJSONValid(invalidJsonString); //false

Please, observe that there could be a "minor" issue due to trailing commas that will be fixed in release 3.0.0.


With Google Gson you can use JsonParser:

import com.google.gson.JsonParser;

JsonParser parser = new JsonParser();
parser.parse(json_string); // throws JsonSyntaxException

You could use the .mayBeJSON(String str) available in the JSONUtils library.


It depends on what you are trying to prove with your validation. Certainly parsing the json as others have suggested is better than using regexes, because the grammar of json is more complicated than can be represented with just regexes.

If the json will only ever be parsed by your java code, then use the same parser to validate it.

But just parsing won't necessarily tell you if it will be accepted in other environments. e.g.

  • many parsers ignore trailing commas in an object or array, but old versions of IE can fail when they hit a trailing comma.
  • Other parsers may accept a trailing comma, but add an undefined/null entry after it.
  • Some parsers may allow unquoted property names.
  • Some parsers may react differently to non-ASCII characters in strings.

If your validation needs to be very thorough, you could:

  • try different parsers until you find one that fails on all the corner cases I mentioned above
  • or you could probably run jsonlint using javax.script.*,
    • http://npmjs.org/package/jsonlint
  • or combine using a parser with running jshint using javax.script.*.
    • https://www.npmjs.org/package/jshint
    • https://github.com/webjars/jshint

A bit about parsing:

Json, and in fact all languages, use a grammar which is a set of rules that can be used as substitutions. in order to parse json, you need to basically work out those substitutions in reverse

Json is a context free grammar, meaning you can have infinitely nested objects/arrays and the json would still be valid. regex only handles regular grammars (hence the 'reg' in the name), which is a subset of context free grammars that doesn't allow infinite nesting, so it's impossible to use only regex to parse all valid json. you could use a complicated set of regex's and loops with the assumption that nobody will nest past say, 100 levels deep, but it would still be very difficult.

if you ARE up for writing your own parser
you could make a recursive descent parser after you work out the grammar