问题描述
我有一个原始字符串.我只想验证字符串是否是有效的 JSON.我正在使用 JSON.NET.
I have a raw string. I just want to validate whether the string is valid JSON or not. I'm using JSON.NET.
推荐答案
通过代码:
最好的办法是在 try-catch
中使用 parse 并在解析失败的情况下捕获异常.(我不知道有任何 TryParse
方法).
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).
(使用 JSON.Net)
最简单的方法是使用 Parse
字符串JToken.Parse
,并检查字符串是否以 {
或 [
开头并以 }结尾code> 或
]
分别 (从这个 回答):
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):
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;
}
}
为 {
或 [
等添加检查的原因是基于 JToken.Parse
将解析值的事实例如 1234"
或 'a string'"
作为有效标记.另一种选择可能是在解析中同时使用 JObject.Parse
和 JArray.Parse
并查看其中是否有人成功,但我相信检查 {}
和 []
应该更容易. (感谢@RhinoDevel 指出)
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 pointing it out)
没有 JSON.Net
您可以使用 .Net framework 4.5 System.Json 命名空间,如:
You can utilize .Net framework 4.5 System.Json namespace ,like:
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());
}
(但是,您必须使用以下命令通过 Nuget 包管理器安装 System.Json
:PM>;Install-Package System.Json -Version 4.0.20126.16343
在包管理器控制台上)(取自这里)
(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)
非编码方式:
通常,当有一个小的 json 字符串并且您试图在 json 字符串中查找错误时,我个人更喜欢使用可用的在线工具.我通常做的是:
Usually, when there is a small json string and you are trying to find a mistake in the json string, then I personally prefer to use available on-line tools. What I usually do is:
- 将 JSON 字符串粘贴到 JSONLint The JSON Validator 并查看是否它是一个有效的 JSON.
- 稍后将正确的 JSON 复制到 http://json2csharp.com/ 和为它生成一个模板类,然后反序列化它使用 JSON.Net.
- Paste JSON string in JSONLint The JSON Validator and 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.NET 确保字符串是有效的 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!