Check if the string is valid JSON in C#

C# validate json string


public static bool IsJsonString(string str)
{
     if (string.IsNullOrWhiteSpace(str)) { return false; }
     str = str.Trim();
     if ((str.StartsWith("{") && str.EndsWith("}")) || 
         (str.StartsWith("[") && str.EndsWith("]")))
      {
         try
         {
            var obj = JToken.Parse(str);
            return true;
          }
          catch (JsonReaderException jex)
          {
             return false;
          }
          catch (Exception ex) //some other exception
          {
             return false;
          }
      }
      else
      {
         return false;
      }
 }
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: