問題描述
我有一個原始字符串.我只想驗證字符串是否是有效的 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!