Efficient way to ensure the validity of JSON strings: JSON.NET and System.Json
In data processing, it is crucial to verify that the original string is valid JSON. Both JSON.NET and System.Json provide reliable solutions.
Code implementation:
The most reliable way is to use JSON.NET's JToken.Parse
method and nest it within a try-catch
block. This allows parsing the string and catching any exceptions indicating the JSON is invalid.
<code class="language-csharp">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; } }</code>
namespace of System.Json
.NET Framework 4.5 also provides the JsonValue.Parse
method:
<code class="language-csharp">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()); }</code>
No code required:
For smaller JSON strings, you can use online tools such as JSONLint and JSON2CSharp to verify their validity and generate template classes for deserialization.
The above is the detailed content of How Can I Efficiently Verify JSON String Validity Using JSON.NET or System.Json?. For more information, please follow other related articles on the PHP Chinese website!