验证 .NET Core 3.0 中的字符串是否为有效的 json(可能的最快方式)

Zoi*_*nky 18 json .net-core

我知道我可以使用外部库(newtonsoft)和 try/catch 来检查字符串是否是有效的 json 结构。我不想反序列化为一个对象(因为 json 可以是一个或多个属性),重点是确保其有效的 json。

我更喜欢使用 System.Text.Json 但不确定什么是最好的,TryParseValue、JsonDocument 等

byt*_*dev 14

如果您的 JSON 位于 a 中string并且您正在使用System.Text.Json,那么检查 JSON 格式良好的最佳方法可能是使用JsonDocument.Parse. 例如:

public static class StringExtensions
{
    public static bool IsJson(this string source)
    {
        if (source == null)
            return false;

        try
        {
            JsonDocument.Parse(source);
            return true;
        }
        catch (JsonException)
        {
            return false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


lid*_*ren 2

我使用 Utf8JsonReader 并简单地在根对象上调用 TrySkip() ;这将检查它至少是格式良好的。

  • 这个答案可以使用一些阐述或代码示例。 (17认同)