C# 判断字符串是否为有效 JSON 格式
可以使用以下方法来判断一个字符串是否是有效的 JSON 格式:
- 使用
try-catch语句块来解析字符串,如果解析成功,则说明字符串是有效的 JSON 格式;如果解析失败,则说明字符串不是有效的 JSON 格式。
using Newtonsoft.Json;
public bool IsJson(string str)
{
try
{
var json = JsonConvert.DeserializeObject(str);
return true;
}
catch (JsonReaderException)
{
return false;
}
}
- 可以使用正则表达式来检查字符串是否符合 JSON 格式的特征。JSON 字符串的特征是以
{开头,以}结尾,并且使用单引号包围的键和值之间使用:分隔。
using System.Text.RegularExpressions;
public bool IsJson(string str)
{
return Regex.IsMatch(str, @'^\{.*\}$');
}
这两种方法都可以用来判断一个字符串是否是有效的 JSON 格式,你可以根据自己的需求选择合适的方法。
原文地址: https://www.cveoy.top/t/topic/fzz4 著作权归作者所有。请勿转载和采集!