且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-26 20:52:16

这个例子在我使用 .NET Core 3.1 时对我有用,如果字符串不是格式正确的 JSON 会抛出异常:

This example has worked for me using .NET Core 3.1 and will throw an exception if a string is not well-formed JSON:

string json = "{ "TestKey": "TestValue" }";

// Ensure the string is valid JSON.
try
{
    var js = new Newtonsoft.Json.JsonSerializer();
    js.Deserialize(new Newtonsoft.Json.JsonTextReader(new System.IO.StringReader(json)));
}
catch (Newtonsoft.Json.JsonReaderException)
{
    throw;
}