Home > Backend Development > C++ > How Can I Efficiently Verify JSON String Validity Using JSON.NET or System.Json?

How Can I Efficiently Verify JSON String Validity Using JSON.NET or System.Json?

Patricia Arquette
Release: 2025-01-10 21:57:43
Original
914 people have browsed it

How Can I Efficiently Verify JSON String Validity Using JSON.NET or System.Json?

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>
Copy after login
The

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template