Hab*_*bib 182
通过代码:
最好的办法是在解析try-catch
失败的情况下在a中使用parse 并捕获异常.(我不知道任何TryParse
方法).
(使用JSON.Net)
最简单的方法是Parse
使用字符串JToken.Parse
,并检查字符串是以字符号开头{
还是以字符串[
结尾}
或]
分别(从此答案中添加):
private static bool IsValidJson(string strInput)
{
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;
}
}
Run Code Online (Sandbox Code Playgroud)
之所以要增加检查{
或[
等是基于这样的事实JToken.Parse
会解析值,例如"1234"
或者"'a string'"
作为一个有效的令牌.另一个选择可能是使用JObject.Parse
和JArray.Parse
解析,看看是否有人成功,但我相信检查{}
,[]
应该更容易. (感谢@RhinoDevel 指出来)
没有JSON.Net
您可以使用.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());
}
Run Code Online (Sandbox Code Playgroud)
(但是,您必须System.Json
使用命令:PM> Install-Package System.Json -Version 4.0.20126.16343
在包管理器控制台上通过Nuget包管理器安装)(取自此处)
非代码方式:
通常,当有一个小的json字符串并且你试图在json字符串中发现错误时,我个人更喜欢使用可用的在线工具.我通常做的是:
小智 30
使用JContainer.Parse(str)
方法检查str是否是有效的Json.如果这会抛出异常,那么它就不是有效的Json.
JObject.Parse
- 可用于检查字符串是否是有效的Json对象
JArray.Parse
- 可用于检查字符串是否是有效的Json数组
JContainer.Parse
- 可用于检查Json对象和数组
Tom*_*ech 15
基于Habib的答案,您可以编写一个扩展方法:
public static bool ValidateJSON(this string s)
{
try
{
JToken.Parse(s);
return true;
}
catch (JsonReaderException ex)
{
Trace.WriteLine(ex);
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以像这样使用:
if(stringObject.ValidateJSON())
{
// Valid JSON!
}
Run Code Online (Sandbox Code Playgroud)
Ωme*_*Man 10
\xe2\x9a\xa0\xef\xb8\x8f 使用System.Text.Json
\xe2\x9a\xa0\xef\xb8\x8f 的替代选项
对于 .Net Core,还可以使用System.Text.Json
命名空间并使用JsonDocument
. 示例是基于命名空间操作的扩展方法:
public static bool IsJsonValid(this string txt)\n{\n try { return JsonDocument.Parse(txt) != null; } catch { return false; }\n}\n
Run Code Online (Sandbox Code Playgroud)\n
只是为@Habib的答案添加一些内容,您还可以检查给定的JSON是否来自有效类型:
public static bool IsValidJson<T>(this string strInput)
{
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我发现JToken.Parse错误地解析了无效的JSON,如下所示:
{
"Id" : ,
"Status" : 2
}
Run Code Online (Sandbox Code Playgroud)
将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;
}
Run Code Online (Sandbox Code Playgroud)