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

JavaJsonValidation

Java Problem Overview


How do I validate a JSON string in Java? Or could I parse it using regular expressions?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

With Google Gson you can use JsonParser:

import com.google.gson.JsonParser;

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

Solution 4 - Java

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

Solution 5 - Java

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:

Solution 6 - Java

String jsonInput = "{\"mob no\":\"9846716175\"}";//Read input Here
JSONReader reader = new JSONValidatingReader();
Object result = reader.read(jsonInput);
System.out.println("Validation Success !!");

Please download stringtree-json library

Solution 7 - Java

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

Solution 8 - Java

Here is a working example for strict json parsing with gson library:

public static JsonElement parseStrict(String json) {
    // throws on almost any non-valid json
    return new Gson().getAdapter(JsonElement.class).fromJson(json); 
}

See also my other detailed answer in How to check if JSON is valid in Java using GSON with more info and extended test case with various non-valid examples.

Solution 9 - Java

The answers are partially correct. I also faced the same problem. Parsing the json and checking for exception seems the usual way but the solution fails for the input json something like

{"outputValueSchemaFormat": "","sortByIndexInRecord": 0,"sortOrder":847874874387209"descending"}kajhfsadkjh

As you can see the json is invalid as there are trailing garbage characters. But if you try to parse the above json using jackson or gson then you will get the parsed map of the valid json and garbage trailing characters are ignored. Which is not the required solution when you are using the parser for checking json validity.

For solution to this problem see here.

PS: This question was asked and answered by me.

Solution 10 - Java

Check whether a given string is valid JSON in Kotlin. I Converted answer of MByD Java to Kotlin

fun isJSONValid(test: String): Boolean {
    try {
        JSONObject(test);
    } catch (ex: JSONException) {
        try {
            JSONArray(test);
        } catch (ex1: JSONException) {
            return false;
        }
    }
    return true;
}

Solution 11 - Java

A solution using the javax.json library:

import javax.json.*;

public boolean isTextJson(String text) {
    try {
        Json.createReader(new StringReader(text)).readObject();
    } catch (JsonException ex) {
        try {
            Json.createReader(new StringReader(text)).readArray();
        } catch (JsonException ex2) {
            return false;
        }
    }
    return true;
}

Solution 12 - Java

Here you can find a tool that can validate a JSON file, or you could just deserialize your JSON file with any JSON library and if the operation is successful then it should be valid (google-json for example that will throw an exception if the input it is parsing is not valid JSON).

Solution 13 - Java

Using Playframework 2.6, the Json library found in the java api can also be used to simply parse the string. The string can either be a json element of json array. Since the returned value is not of importance here we just catch the parse error to determine that the string is a correct json string or not.

    import play.libs.Json;

    public static Boolean isValidJson(String value) {
        try{
            Json.parse(value);
            return true;
        } catch(final Exception e){
            return false;
        }
    }

Solution 14 - Java

IMHO, the most elegant way is using the Java API for JSON Processing (JSON-P), one of the JavaEE standards that conforms to the JSR 374.

try(StringReader sr = new StringReader(jsonStrn)) {
    Json.createReader(sr).readObject();
} catch(JsonParsingException e) {
    System.out.println("The given string is not a valid json");
    e.printStackTrace();
}

Using Maven, add the dependency on JSON-P:

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.4</version>
</dependency>

Visit the JSON-P official page for more informations.

Solution 15 - Java

As you can see, there is a lot of solutions, they mainly parse the JSON to check it and at the end you will have to parse it to be sure.

But, depending on the context, you may improve the performances with a pre-check.

What I do when I call APIs, is just checking that the first character is '{' and the last is '}'. If it's not the case, I don't bother creating a parser.

Solution 16 - Java

I have found a very simple solution for it.

Please first install this library net.sf.json-lib for it.

    import net.sf.json.JSONException;
    
    import net.sf.json.JSONSerializer;

    private static boolean isValidJson(String jsonStr) {
        boolean isValid = false;
        try {
            JSONSerializer.toJSON(jsonStr);
            isValid = true;
        } catch (JSONException je) {
            isValid = false;
        }
        return isValid;
    }

    public static void testJson() {
        String vjson = "{\"employees\": [{ \"firstName\":\"John\" , \"lastName\":\"Doe\" },{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" },{ \"firstName\":\"Peter\" , \"lastName\":\"Jones\" }]}";
        String ivjson = "{\"employees\": [{ \"firstName\":\"John\" ,, \"lastName\":\"Doe\" },{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" },{ \"firstName\":\"Peter\" , \"lastName\":\"Jones\" }]}";
        System.out.println(""+isValidJson(vjson)); // true
        System.out.println(""+isValidJson(ivjson)); // false
    }

Done. Enjoy

Solution 17 - Java

import static net.minidev.json.JSONValue.isValidJson;

and then call this function passing in your JSON String :)

Solution 18 - Java

public static boolean isJSONValid(String test) {
    try {
        isValidJSON(test);
        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(test);
        while (!parser.isClosed()) {
            parser.nextToken();
        }
    } catch (Exception e) {
        LOGGER.error("exception: ", e);
        return false;
    }
    return true;
}

private static void isValidJSON(String test) {
    try {
        new JSONObject(test);
    } catch (JSONException ex) {
        try {
            LOGGER.error("exception: ", ex);
            new JSONArray(test);
        } catch (JSONException ex1) {
            LOGGER.error("exception: ", ex1);
            throw new Exception("Invalid JSON.");
        }
    }
}

Above solution covers both the scenarios:

  • duplicate key
  • mismatched quotes or missing parentheses etc.

Solution 19 - Java

You can try below code, worked for me:

 import org.json.JSONObject;
 import org.json.JSONTokener;

 public static JSONObject parseJsonObject(String substring)
 {
  return new JSONObject(new JSONTokener(substring));
 }

Solution 20 - Java

in Gson Version

try {
    String errorBody = response.errorBody().string();
    MyErrorResponse errorResponse = new Gson().fromJson(errorBody, MyErrorResponse.class);
} catch (JsonSyntaxException e) {
    e.printStackTrace();
}

Solution 21 - Java

You can use WellFormedJson class from Validol declarative validation library.

The declaration itself could look like the following:

new WellFormedJson(
    new Unnamed<>(Either.right(new Present<>(jsonRequestString)))
)

The check phase looks like that:

    Result<JsonElement> result =
        (new WellFormedJson(
            new Named<>(
                "vasya",
                Either.right(
                    new Present<>(
                        "{\"guest\":{\"name\":\"Vadim Samokhin\",\"email\":\"samokhinvadim@gmail.com\"},\"source\":1,\"items\":[{\"id\":1900},{\"id\":777}]}"
                    )
                )
            )
        ))
            .result();

    assertTrue(result.isSuccessful());
    assertEquals(
        "{\"guest\":{\"name\":\"Vadim Samokhin\",\"email\":\"samokhinvadim@gmail.com\"},\"source\":1,\"items\":[{\"id\":1900},{\"id\":777}]}",
        result.value().raw().toString()
    );
    assertEquals(
        "{\"name\":\"Vadim Samokhin\",\"email\":\"samokhinvadim@gmail.com\"}",
        result.value().raw().getAsJsonObject().get("guest").toString()
    );

It might seem like an overkill for such a simple task, but it shines when you have to validate a complex request. Check out validol's quick start section.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsappuView Question on Stackoverflow
Solution 1 - JavaMByDView Answer on Stackoverflow
Solution 2 - JavaJeanValjeanView Answer on Stackoverflow
Solution 3 - JavaCristianView Answer on Stackoverflow
Solution 4 - JavanpintiView Answer on Stackoverflow
Solution 5 - JavaNicholas Daley-OkoyeView Answer on Stackoverflow
Solution 6 - JavaJamsheerView Answer on Stackoverflow
Solution 7 - JavaAustin_AndersonView Answer on Stackoverflow
Solution 8 - JavaVadzimView Answer on Stackoverflow
Solution 9 - Javaiec2011007View Answer on Stackoverflow
Solution 10 - JavaBhavesh HirparaView Answer on Stackoverflow
Solution 11 - JavaRok PovsicView Answer on Stackoverflow
Solution 12 - JavatalnicolasView Answer on Stackoverflow
Solution 13 - JavaBaahView Answer on Stackoverflow
Solution 14 - JavaDomenicoView Answer on Stackoverflow
Solution 15 - JavaOrdenView Answer on Stackoverflow
Solution 16 - JavaAtif MeharView Answer on Stackoverflow
Solution 17 - JavaJasonView Answer on Stackoverflow
Solution 18 - JavaShailendraView Answer on Stackoverflow
Solution 19 - JavadicleView Answer on Stackoverflow
Solution 20 - JavaYi Rong WuView Answer on Stackoverflow
Solution 21 - JavaVadim SamokhinView Answer on Stackoverflow