我知道我可以使用外部库(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)
| 归档时间: |
|
| 查看次数: |
20377 次 |
| 最近记录: |