C# 如何使用 JSON.NET 确保字符串是有效的 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14977848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make sure that string is valid JSON using JSON.NET
提问by user960567
I have a raw string. I just want to validate whether the string is valid JSON or not. I'm using JSON.NET.
我有一个原始字符串。我只想验证字符串是否是有效的 JSON。我正在使用 JSON.NET。
采纳答案by Habib
Through Code:
通过代码:
Your best bet is to use parse inside a try-catch
and catch exception in case of failed parsing. (I am not aware of any TryParse
method).
最好的办法是在解析try-catch
失败的情况下在 a 中使用 parse并捕获异常。(我不知道任何TryParse
方法)。
(Using JSON.Net)
(使用 JSON.Net)
Simplest way would be to Parse
the string using JToken.Parse
, and also to check if the string starts with {
or [
and ends with }
or ]
respectively (added from this answer):
最简单的方法是Parse
使用字符串JToken.Parse
,并检查字符串是否分别以or开头和以{
or[
结尾(从这个答案中添加):}
]
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;
}
}
The reason to add checks for {
or [
etc was based on the fact that JToken.Parse
would parse the values such as "1234"
or "'a string'"
as a valid token. The other option could be to use both JObject.Parse
and JArray.Parse
in parsing and see if anyone of them succeeds, but I believe checking for {}
and []
should be easier.(Thanks @RhinoDevel for pointingit out)
添加检查{
或[
等的原因是基于JToken.Parse
将解析诸如"1234"
或"'a string'"
作为有效令牌之类的值的事实。另一种选择可能是在解析中同时使用JObject.Parse
和JArray.Parse
并查看它们中是否有人成功,但我相信检查{}
并且[]
应该更容易。(感谢@RhinoDevel指出)
Without JSON.Net
没有 JSON.Net
You can utilize .Net framework 4.5 System.Json namespace,like:
您可以利用 .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());
}
(But, you have to install System.Json
through Nuget package manager using command: PM> Install-Package System.Json -Version 4.0.20126.16343
on Package Manager Console)(taken from here)
(但是,您必须System.Json
使用命令通过 Nuget 包管理器安装:PM> Install-Package System.Json -Version 4.0.20126.16343
在包管理器控制台上)(取自此处)
Non-Code way:
非代码方式:
Usually, when there is a small json string and you are trying to find a mistake in the json string, then I personallyprefer to use available on-line tools. What I usually do is:
通常,当有一个小的 json 字符串并且您试图在 json 字符串中查找错误时,那么我个人更喜欢使用可用的在线工具。我通常做的是:
- Paste JSON string in JSONLint The JSON Validatorand see if its a valid JSON.
- Later copy the correct JSON to http://json2csharp.com/and generate a template class for it and then de-serialize it using JSON.Net.
- 将 JSON 字符串粘贴到JSONLint JSON 验证器中,看看它是否是有效的 JSON。
- 稍后将正确的 JSON 复制到http://json2csharp.com/并为其生成模板类,然后使用 JSON.Net 对其进行反序列化。
回答by Senthilkumar Viswanathan
Use JContainer.Parse(str)
method to check if the str is a valid Json. If this throws exception then it is not a valid Json.
使用JContainer.Parse(str)
方法检查 str 是否是有效的 Json。如果这引发异常,则它不是有效的 Json。
JObject.Parse
- Can be used to check if the string is a valid Json objectJArray.Parse
- Can be used to check if the string is a valid Json ArrayJContainer.Parse
- Can be used to check for both Json object & Array
JObject.Parse
- 可用于检查字符串是否为有效的 Json 对象JArray.Parse
- 可用于检查字符串是否为有效的 Json 数组JContainer.Parse
- 可用于检查 Json 对象和数组
回答by Tom Beech
Building on Habib's answer, you could write an extension method:
基于 Habib 的回答,您可以编写一个扩展方法:
public static bool ValidateJSON(this string s)
{
try
{
JToken.Parse(s);
return true;
}
catch (JsonReaderException ex)
{
Trace.WriteLine(ex);
return false;
}
}
Which can then be used like this:
然后可以像这样使用:
if(stringObject.ValidateJSON())
{
// Valid JSON!
}
回答by HappyCoding
Regarding Tom Beech's answer; I came up with the following instead:
关于汤姆·比奇的回答;我想出了以下内容:
public bool ValidateJSON(string s)
{
try
{
JToken.Parse(s);
return true;
}
catch (JsonReaderException ex)
{
Trace.WriteLine(ex);
return false;
}
}
With a usage of the following:
使用以下内容:
if (ValidateJSON(strMsg))
{
var newGroup = DeserializeGroup(strMsg);
}
回答by Jalal
Just to add something to @Habib's answer, you can also check if given JSON is from a valid type:
只是在@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;
}
}
回答by Andrew Roberts
I found that JToken.Parse incorrectly parses invalid JSON such as the following:
我发现 JToken.Parse 错误地解析了无效的 JSON,如下所示:
{
"Id" : ,
"Status" : 2
}
Paste the JSON string into http://jsonlint.com/- it is invalid.
将 JSON 字符串粘贴到http://jsonlint.com/- 它是无效的。
So I use:
所以我使用:
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;
}
回答by MostafaZ4
This method doesn't require external libraries
此方法不需要外部库
using System.Web.Script.Serialization;
bool IsValidJson(string json)
{
try {
var serializer = new JavaScriptSerializer();
dynamic result = serializer.DeserializeObject(json);
return true;
} catch { return false; }
}
回答by Randy Larson
JToken.Type
is available after a successful parse. This can be used to eliminate some of the preamble in the answers above and provide insight for finer control of the result. Entirely invalid input (e.g., "{----}".IsValidJson();
will still throw an exception).
JToken.Type
成功解析后可用。这可用于消除上述答案中的一些前导码,并为更好地控制结果提供洞察力。完全无效的输入(例如,"{----}".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 reference for JToken.Type
: https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JTokenType.htm
Json.Net 参考JToken.Type
:https: //www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JTokenType.htm
回答by jaybro
Here is a TryParse extension method based on Habib's answer:
这是基于 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;
}
}
Usage:
用法:
JToken jToken;
if (strJson.TryParse(out jToken))
{
// work with jToken
}
else
{
// not valid json
}
回答by Yousha Aleayoub
I'm using this one:
我正在使用这个:
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;
}
}