Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate a string to be json or not in asp.net

is there any way to validate a string to be json or not ? other than try/catch .

I'm using ServiceStack Json Serializer and couldn't find a method related to validation .

like image 851
mohsen dorparasti Avatar asked Aug 06 '12 20:08

mohsen dorparasti


People also ask

How check string is JSON or not in C#?

Use JContainer. Parse(str) method to check if the str is a valid Json. If this throws exception then it is not a valid Json.

What is the meaning of JSON data invalid?

It means that the editor failed to get a response to the server or the response wasn't in a valid JSON format. Basically, if the editor can't communicate with the server, it will show this error message instead. To fix the problem, you essentially need to fix whatever is getting in the way of the communication.

How do you check if the JSON is valid or not?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema. To get validation error messages use the IsValid(JToken, JSchema, IList<String> ) or Validate(JToken, JSchema, SchemaValidationEventHandler) overloads.

What is valid JSON?

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.


Video Answer


2 Answers

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
like image 132
skub Avatar answered Oct 20 '22 20:10

skub


A working code snippet

public bool isValidJSON(String json)
{
    try
    {
        JToken token = JObject.Parse(json);
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

Source

like image 41
Durai Amuthan.H Avatar answered Oct 20 '22 22:10

Durai Amuthan.H