JSON.NET을 사용하여 문자열이 유효한 JSON인지 확인하는 방법
원시 문자열이 있습니다. 문자열이 유효한 JSON인지 여부를 확인하고 싶습니다. JSON.NET을 사용하고 있습니다.
코드를 통해 :
가장 좋은 방법은 구문 분석 try-catch
에 실패한 경우 내부에서 구문 분석을 사용 하고 예외를 포착 하는 것 입니다. (나는 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;
}
}
그 이유는 대한 검사를 추가 {
하거나 [
등 사실에 기초하고 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());
}
(하지만 패키지 관리자 콘솔에서 System.Json
다음 명령을 사용하여 Nuget 패키지 관리자를 통해 설치해야 함 PM> Install-Package System.Json -Version 4.0.20126.16343
) ( 여기 에서 가져옴 )
비 코드 방식 :
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:
- 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.
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.
JObject.Parse
- Can be used to check if the string is a valid Json object
JArray.Parse
- Can be used to check if the string is a valid Json Array
JContainer.Parse
- Can be used to check for both Json object & Array
Building on Habib's answer, you could write an extension method:
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!
}
Just to add something to @Habib's answer, you can also check if given JSON is from a valid type:
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;
}
}
I found that JToken.Parse incorrectly parses invalid JSON such as the following:
{
"Id" : ,
"Status" : 2
}
Paste the JSON string into http://jsonlint.com/ - it is invalid.
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;
}
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);
}
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; }
}
'IT박스' 카테고리의 다른 글
form_for이지만 다른 작업에 게시 (0) | 2020.07.18 |
---|---|
Python에서 퍼지 문자열 비교 고성능, Levenshtein 또는 difflib 사용 (0) | 2020.07.18 |
Visual Studio에서 디버그 모드로 NUnit을 어떻게 실행합니까? (0) | 2020.07.18 |
OpenSSL 연결을 거부하는 Homebrew (0) | 2020.07.18 |
LINQ to SQL : 여러 열에서 여러 조인 (0) | 2020.07.18 |