Way to quickly check if string is XML or JSON in C#

Very simple:

  1. Valid JSON starts always with '{' or '['
  2. Valid XML starts always with '<'

I'm talking about non-space data.


public static bool IsJson(this string input){
    input = input.Trim();
    return input.StartsWith("{") && input.EndsWith("}") 
           || input.StartsWith("[") && input.EndsWith("]");
}

it's a bit dirty but simple and quick

It is essentially enough to test the first character. Testing the last is a very rude way of testing well formedness. It doesn't guarantee it it simply heightens the chance that it is well formed.

If you wanted a more robust version you could take advantage of the short circuiting of if's to only evaluate well-formedness if the initial check is good. The below code relies on JSON.net

public static bool IsJson(this string input){
    input = input.Trim();
    Predicate IsWellFormed = () => {
             try {
                JToken.Parse(input);
             } catch {
                return false;
             }
             return true;
    }
    return (input.StartsWith("{") && input.EndsWith("}") 
            || input.StartsWith("[") && input.EndsWith("]"))
           && IsWellFormed()
}

Thought I'd throw my solution in here too...

if (jsonData.Trim().Substring(0, 1).IndexOfAny(new[] {'[', '{'}) != 0)
     throw new Exception("The source file must be in JSON format");

or an extension...

public static bool IsJson(this string jsonData)
{
     return jsonData.Trim().Substring(0, 1).IndexOfAny(new[] { '[', '{' }) == 0;
}

usage:

if (!jsonData.IsJson())
     throw new Exception("The source file must be in JSON format");