在 .NET Core 3.0 中验证字符串是否是有效的 json(最快的方式) [英] Validate if string is valid json (fastest way possible) in .NET Core 3.0

查看:156
本文介绍了在 .NET Core 3.0 中验证字符串是否是有效的 json(最快的方式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know i can use an external library(newtonsoft) with a try/catch to check if a string is valid json structure. I do not want to deserialize to an object (since the json can be one or many properties) point is to just make sure its valid json.

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

I would prefer to use the System.Text.Json but not sure what would be the best, TryParseValue, JsonDocument, etc

推荐答案

这个例子在我使用 .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;
}

这篇关于在 .NET Core 3.0 中验证字符串是否是有效的 json(最快的方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆