8

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 .

3

3 Answers 3

18

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:

Sign up to request clarification or add additional context in comments.

Comments

1

A working code snippet

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

Source

1 Comment

This misses scenarios when the payload is missing a closing } or ] .
0

You can find a couple of regular expressions to validate JSON over here: Regex to validate JSON

It's written in PHP but should be adaptable to C#.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.