How to make sure that string is valid JSON using JSON.NET
Through Code:
Your best bet is to use parse inside a try-catch
and catch exception in case of failed parsing. (I am not aware of any TryParse
method).
(Using JSON.Net)
Simplest way would be to Parse
the string using JToken.Parse
, and also to check if the string starts with {
or [
and ends with }
or ]
respectively (added from this answer):
private static bool IsValidJson(string strInput)
{
if (string.IsNullOrWhiteSpace(strInput)) { return false;}
strInput = strInput.Trim();
if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
(strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
{
try
{
var obj = JToken.Parse(strInput);
return true;
}
catch (JsonReaderException jex)
{
//Exception in parsing json
Console.WriteLine(jex.Message);
return false;
}
catch (Exception ex) //some other exception
{
Console.WriteLine(ex.ToString());
return false;
}
}
else
{
return false;
}
}
The reason to add checks for {
or [
etc was based on the fact that JToken.Parse
would parse the values such as "1234"
or "'a string'"
as a valid token. The other option could be to use both JObject.Parse
and JArray.Parse
in parsing and see if anyone of them succeeds, but I believe checking for {}
and []
should be easier. (Thanks @RhinoDevel for pointing it out)
Without JSON.Net
You can utilize .Net framework 4.5 System.Json namespace ,like:
string jsonString = "someString";
try
{
var tmpObj = JsonValue.Parse(jsonString);
}
catch (FormatException fex)
{
//Invalid json format
Console.WriteLine(fex);
}
catch (Exception ex) //some other exception
{
Console.WriteLine(ex.ToString());
}
(But, you have to install System.Json
through Nuget package manager using command: PM> Install-Package System.Json -Version 4.0.20126.16343
on Package Manager Console) (taken from here)
Non-Code way:
Usually, when there is a small json string and you are trying to find a mistake in the json string, then I personally prefer to use available on-line tools. What I usually do is:
- Paste JSON string in JSONLint The JSON Validator and see if
its a valid JSON. - Later copy the correct JSON to http://json2csharp.com/ and
generate a template class for it and then de-serialize it
using JSON.Net.
Need a string JSON Validator
The simplest solution would be to write a function which calls JObject.Parse
and returns false if it throws a Newtonsoft.Json.JsonReaderException
.
Validate a string to be json or not in asp.net
Probably the quickest and dirtiest way is to check if the string starts with '{':
public static bool IsJson(string input){
input = input.Trim();
return input.StartsWith("{") && input.EndsWith("}")
|| input.StartsWith("[") && input.EndsWith("]");
}
Another option is that you could try using the JavascriptSerializer class:
JavaScriptSerializer ser = new JavaScriptSerializer();
SomeJSONClass = ser.Deserialize<SomeJSONClass >(json);
Or you could have a look at JSON.NET:
- http://james.newtonking.com/projects/json-net.aspx
- http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingJSON.htm
How to check if a string is a valid JSON string?
A comment first. The question was about not using try/catch
.
If you do not mind to use it, read the answer below.
Here we just check a JSON
string using a regexp, and it will work in most cases, not all cases.
Have a look around the line 450 in https://github.com/douglascrockford/JSON-js/blob/master/json2.js
There is a regexp that check for a valid JSON, something like:
if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
//the json is ok
}else{
//the json is not ok
}
EDIT: The new version of json2.js makes a more advanced parsing than above, but still based on a regexp replace ( from the comment of @Mrchief )
Related Topics
How to Write a Backslash (\) in a String
Cross-Thread Operation Not Valid
How to Clean SQLdependency from SQL Server Memory
Deserializing JSON into an Object
How to Change the Timeout on a .Net Webclient Object
Split String Containing Command-Line Parameters into String[] in C#
Can't Get Czech Characters While Generating a PDF
Accessing a Variable from Another Script C#
#If Debug VS. Conditional("Debug")
Unity Game Manager. Script Works Only One Time
Call Asynchronous Method in Constructor
Entity Framework Join 3 Tables
Reference Assemblies for Framework ".Netframework,Version=V4.7.1" Were Not Found
Mono High Resolution Timer (On Linux)