我有一个原始的字符串。我只想验证字符串是否是有效的JSON。我用的是JSON.NET。
通过代码:
最好的办法是在try-catch和catch异常中使用parse,以防解析失败。(我不知道任何TryParse方法)。
(使用JSON.Net)
最简单的方法是使用JToken解析字符串。解析,并检查字符串是否以{或[开始,并分别以}或]结束(从这个答案中添加):
private static bool IsValidJson(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 = JToken.Parse(strInput);
return true;
}
catch (JsonReaderException jex)
{
//Exception in parsing json
Console.WriteLine(jex.Message);
return false;
}
catch (Exception ex) //some other exception
{
Console.WriteLine(ex.ToString());
return false;
}
}
else
{
return false;
}
}
为{或[etc]添加检查的原因是基于JToken。Parse会将诸如“1234”或“'a string'”之类的值解析为有效的标记。另一种选择是同时使用两个JObject。解析和JArray。在解析中进行解析,看看是否有人成功,但我相信检查{}和[]应该更容易。(感谢@RhinoDevel指出这一点)
没有JSON。网
你可以利用。net framework 4.5 System。Json命名空间,例如:
string jsonString = "someString";
try
{
var tmpObj = JsonValue.Parse(jsonString);
}
catch (FormatException fex)
{
//Invalid json format
Console.WriteLine(fex);
}
catch (Exception ex) //some other exception
{
Console.WriteLine(ex.ToString());
}
(但是,你必须安装系统。PM>安装包系统。Json -版本4.0.20126.16343在包管理器控制台)(从这里)
非代码:
通常,当有一个小的json字符串,你试图在json字符串中找到一个错误,那么我个人更喜欢使用可用的在线工具。我通常做的是:
在JSONLint的JSON验证器中粘贴JSON字符串,看看是否 它是一个有效的JSON。 稍后将正确的JSON复制到http://json2csharp.com/和 为它生成一个模板类,然后反序列化它 使用JSON.Net。
使用JContainer.Parse(str)方法来检查str是否是一个有效的Json。如果这个抛出异常,那么它不是一个有效的Json。
JObject。Parse -可以用来检查字符串是否是一个有效的Json对象 JArray。Parse -可以用来检查字符串是否是一个有效的Json数组 JContainer。解析-可以用来检查Json对象和数组
基于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!
}
关于汤姆·比奇的回答;相反,我想到了以下几点:
public bool ValidateJSON(string s)
{
try
{
JToken.Parse(s);
return true;
}
catch (JsonReaderException ex)
{
Trace.WriteLine(ex);
return false;
}
}
有以下用法:
if (ValidateJSON(strMsg))
{
var newGroup = DeserializeGroup(strMsg);
}
只是为了给@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;
}
}
我找到了JToken。Parse错误地解析无效的JSON,如下所示:
{
"Id" : ,
"Status" : 2
}
将JSON字符串粘贴到http://jsonlint.com/ -无效。
所以我用:
public static bool IsValidJson(this string input)
{
input = input.Trim();
if ((input.StartsWith("{") && input.EndsWith("}")) || //For object
(input.StartsWith("[") && input.EndsWith("]"))) //For array
{
try
{
//parse the input into a JObject
var jObject = JObject.Parse(input);
foreach(var jo in jObject)
{
string name = jo.Key;
JToken value = jo.Value;
//if the element has a missing value, it will be Undefined - this is invalid
if (value.Type == JTokenType.Undefined)
{
return false;
}
}
}
catch (JsonReaderException jex)
{
//Exception in parsing json
Console.WriteLine(jex.Message);
return false;
}
catch (Exception ex) //some other exception
{
Console.WriteLine(ex.ToString());
return false;
}
}
else
{
return false;
}
return true;
}
此方法不需要外部库
using System.Web.Script.Serialization;
bool IsValidJson(string json)
{
try {
var serializer = new JavaScriptSerializer();
dynamic result = serializer.DeserializeObject(json);
return true;
} catch { return false; }
}
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答案的TryParse扩展方法:
public static bool TryParse(this string strInput, out JToken output)
{
if (String.IsNullOrWhiteSpace(strInput))
{
output = null;
return false;
}
strInput = strInput.Trim();
if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
(strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
{
try
{
output = JToken.Parse(strInput);
return true;
}
catch (JsonReaderException jex)
{
//Exception in parsing json
//optional: LogError(jex);
output = null;
return false;
}
catch (Exception ex) //some other exception
{
//optional: LogError(ex);
output = null;
return false;
}
}
else
{
output = null;
return false;
}
}
用法:
JToken jToken;
if (strJson.TryParse(out jToken))
{
// work with jToken
}
else
{
// not valid json
}
我用的是这个:
internal static bool IsValidJson(string data)
{
data = data.Trim();
try
{
if (data.StartsWith("{") && data.EndsWith("}"))
{
JToken.Parse(data);
}
else if (data.StartsWith("[") && data.EndsWith("]"))
{
JArray.Parse(data);
}
else
{
return false;
}
return true;
}
catch
{
return false;
}
}
⚠️使用System.Text.Json的替代选项⚠️
对于. net Core,也可以使用System.Text.Json命名空间,并使用JsonDocument进行解析。示例:基于命名空间操作的扩展方法:
public static bool IsJsonValid(this string txt)
{
try { return JsonDocument.Parse(txt) != null; } 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.Parse (jsonString); 不完全验证json。
相反,你可以使用下面的方法来检查json字符串的有效性,而读取。 参考:https://www.newtonsoft.com/jsonschema/help/html/ValidatingJson.htm
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
JSchemaValidatingReader validatingReader = new JSchemaValidatingReader(reader);
validatingReader.Schema = JSchema.Parse(schemaJson);
IList<string> messages = new List<string>();
validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message);
JsonSerializer serializer = new JsonSerializer();
Person p = serializer.Deserialize<Person>(validatingReader);
推荐文章
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和
- 我如何使用IValidatableObject?
- 如何指定最小值,但没有使用范围数据注释属性的最大小数?