我有一个原始的字符串。我只想验证字符串是否是有效的JSON。我用的是JSON.NET。
当前回答
此方法不需要外部库
using System.Web.Script.Serialization;
bool IsValidJson(string json)
{
try {
var serializer = new JavaScriptSerializer();
dynamic result = serializer.DeserializeObject(json);
return true;
} catch { return false; }
}
其他回答
此方法不需要外部库
using System.Web.Script.Serialization;
bool IsValidJson(string json)
{
try {
var serializer = new JavaScriptSerializer();
dynamic result = serializer.DeserializeObject(json);
return true;
} catch { return false; }
}
即使返回异常也返回json字符串的扩展:
public static string OnlyValidJson(this string strInput) { if (string.IsNullOrWhiteSpace(strInput)) { return @"[""Json is empty""]"; } strInput = strInput.Trim(); if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || (strInput.StartsWith("[") && strInput.EndsWith("]"))) { try { string strEscape = strInput.Replace("\\n", "").Replace("\\r", "").Replace("\n", "").Replace("\r", ""); JToken.Parse(strEscape); return strEscape; } catch (JsonReaderException jex) { return @$"{{""JsonReaderException"":""{jex.Message}""}}"; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return @$"{{""Exception"":""{ex.ToString()}""}}"; } } else { return @"[""Json not start with { or [.""]"; } }
JToken。类型在解析成功后可用。这可以用来消除上面答案中的一些序言,并为更好地控制结果提供见解。完全无效的输入(例如,“{----}”. isvalidjson ();仍然会抛出异常)。
public static bool IsValidJson(this string src)
{
try
{
var asToken = JToken.Parse(src);
return asToken.Type == JTokenType.Object || asToken.Type == JTokenType.Array;
}
catch (Exception) // Typically a JsonReaderException exception if you want to specify.
{
return false;
}
}
Json。Net引用JToken。类型:https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JTokenType.htm
只是为了给@Habib的答案添加一些东西,你也可以检查给定的JSON是否来自有效的类型:
public static bool IsValidJson<T>(this string strInput)
{
if(string.IsNullOrWhiteSpace(strInput)) return false;
strInput = strInput.Trim();
if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
(strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
{
try
{
var obj = JsonConvert.DeserializeObject<T>(strInput);
return true;
}
catch // not valid
{
return false;
}
}
else
{
return false;
}
}
基于Habib的回答,你可以编写一个扩展方法:
public static bool ValidateJSON(this string s)
{
try
{
JToken.Parse(s);
return true;
}
catch (JsonReaderException ex)
{
Trace.WriteLine(ex);
return false;
}
}
然后可以这样使用:
if(stringObject.ValidateJSON())
{
// Valid JSON!
}
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和