我有一个原始的字符串。我只想验证字符串是否是有效的JSON。我用的是JSON.NET。


当前回答

基于Habib的回答,你可以编写一个扩展方法:

public static bool ValidateJSON(this string s)
{
    try
    {
        JToken.Parse(s);
        return true;
    }
    catch (JsonReaderException ex)
    {
        Trace.WriteLine(ex);
        return false;
    }
}

然后可以这样使用:

if(stringObject.ValidateJSON())
{
    // Valid JSON!
}

其他回答

只是为了给@Habib的答案添加一些东西,你也可以检查给定的JSON是否来自有效的类型:

public static bool IsValidJson<T>(this 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 = JsonConvert.DeserializeObject<T>(strInput);
            return true;
        }
        catch // not valid
        {             
            return false;
        }
    }
    else
    {
        return false;
    }
}

关于汤姆·比奇的回答;相反,我想到了以下几点:

public bool ValidateJSON(string s)
{
    try
    {
        JToken.Parse(s);
        return true;
    }
    catch (JsonReaderException ex)
    {
        Trace.WriteLine(ex);
        return false;
    }
}

有以下用法:

if (ValidateJSON(strMsg))
{
    var newGroup = DeserializeGroup(strMsg);
}

⚠️使用System.Text.Json的替代选项⚠️

对于. net Core,也可以使用System.Text.Json命名空间,并使用JsonDocument进行解析。示例:基于命名空间操作的扩展方法:

public static bool IsJsonValid(this string txt)
{
    try { return JsonDocument.Parse(txt) != null; } catch {}

    return false;
}

即使返回异常也返回json字符串的扩展:

        public static string OnlyValidJson(this string strInput)
        {
            if (string.IsNullOrWhiteSpace(strInput)) { return @"[""Json is empty""]"; }
            strInput = strInput.Trim();
            if ((strInput.StartsWith("{") && strInput.EndsWith("}")) ||
                (strInput.StartsWith("[") && strInput.EndsWith("]")))
            {
                try
                {
                    string strEscape = strInput.Replace("\\n", "").Replace("\\r", "").Replace("\n", "").Replace("\r", "");
                    JToken.Parse(strEscape);
                    return strEscape;
                }
                catch (JsonReaderException jex)
                {
                    return @$"{{""JsonReaderException"":""{jex.Message}""}}";
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    return @$"{{""Exception"":""{ex.ToString()}""}}";
                }
            }
            else
            {
                return @"[""Json not start with { or [.""]";
            }
        }

基于Habib的回答,你可以编写一个扩展方法:

public static bool ValidateJSON(this string s)
{
    try
    {
        JToken.Parse(s);
        return true;
    }
    catch (JsonReaderException ex)
    {
        Trace.WriteLine(ex);
        return false;
    }
}

然后可以这样使用:

if(stringObject.ValidateJSON())
{
    // Valid JSON!
}