JSON 문자열의 유효성을 보장하는 효율적인 방법: JSON.NET 및 System.Json
데이터 처리에서는 원본 문자열이 유효한 JSON인지 확인하는 것이 중요합니다. JSON.NET과 System.Json은 모두 안정적인 솔루션을 제공합니다.
코드 구현:
가장 안정적인 방법은 JSON.NET의 JToken.Parse
메서드를 사용하여 try-catch
블록 내에 중첩하는 것입니다. 이를 통해 문자열을 구문 분석하고 JSON이 유효하지 않음을 나타내는 예외를 포착할 수 있습니다.
using Newtonsoft.Json; using Newtonsoft.Json.Linq; private static bool IsValidJson(string strInput) { if (string.IsNullOrWhiteSpace(strInput)) { return false; } strInput = strInput.Trim(); if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || // 对象 (strInput.StartsWith("[") && strInput.EndsWith("]"))) // 数组 { try { var obj = JToken.Parse(strInput); return true; } catch (JsonReaderException jex) { // 解析异常 Console.WriteLine(jex.Message); return false; } catch (Exception ex) { // 其他异常 Console.WriteLine(ex.ToString()); return false; } } else { return false; } }
.NET Framework 4.5의 System.Json
네임스페이스는 JsonValue.Parse
메서드도 제공합니다.
using System.Runtime.Serialization.Json; string jsonString = "someString"; try { var tmpObj = JsonValue.Parse(jsonString); } catch (FormatException fex) { // 无效的JSON格式 Console.WriteLine(fex); } catch (Exception ex) { // 其他异常 Console.WriteLine(ex.ToString()); }
코드 필요 없음:
더 작은 JSON 문자열의 경우 JSONLint 및 JSON2CSharp와 같은 온라인 도구를 사용하여 유효성을 확인하고 역직렬화를 위한 템플릿 클래스를 생성할 수 있습니다.
위 내용은 JSON.NET 또는 System.Json을 사용하여 JSON 문자열 유효성을 효율적으로 확인하려면 어떻게 해야 합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!