Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate if string is valid json (fastest way possible) in .NET Core 3.0

Tags:

json

.net-core

I know i can use an external library(newtonsoft) with a try/catch to check if a string is valid json structure. I do not want to deserialize to an object (since the json can be one or many properties) point is to just make sure its valid json.

I would prefer to use the System.Text.Json but not sure what would be the best, TryParseValue, JsonDocument, etc

like image 910
Zoinky Avatar asked Nov 17 '25 03:11

Zoinky


2 Answers

If your JSON is in a string and you are using System.Text.Json then probably the best way to check the JSON is well-formed would be to use JsonDocument.Parse. For example:

public static class StringExtensions
{
    public static bool IsJson(this string source)
    {
        if (source == null)
            return false;

        try
        {
            using (JsonDocument doc = JsonDocument.Parse(source))
            {
                // dispose any created doc
            }
            return true;
        }
        catch (JsonException)
        {
            return false;
        }
    }
}
like image 159
bytedev Avatar answered Nov 18 '25 21:11

bytedev


An small improvement in @bytedev answer, disposing JsonDocument based on Microsoft JsonDocument remark:

This class utilizes resources from pooled memory to minimize the impact of the garbage collector (GC) in high-usage scenarios. Failure to properly dispose this object will result in the memory not being returned to the pool, which will increase GC impact across various parts of the framework

public static bool IsJsonValid(this string json)
{
    if (string.IsNullOrWhiteSpace(json))
        return false;

    try
    {
        using var jsonDoc = JsonDocument.Parse(json);
        return true;
    }
    catch (JsonException)
    {
        return false;
    }
}
like image 45
Jonathan Ramos Avatar answered Nov 18 '25 20:11

Jonathan Ramos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!