Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.net Schema IsValid slow

I have a web service that communicates with client with JSON messages, the run-time itself is not aware of the data-model which is why I use json.net Schema to validate messages from client and inside the service itself, however Its causing a great amount of overhead in terms of performance.

Simplified code that still contain enough context to understand what I am doing.

public class Template
{
    /// <summary>
    /// Template known as
    /// </summary>
    public string Name { get; private set; }
    /// <summary>
    /// Razor Template
    /// </summary>
    public string RazorTemplate { get; private set; }
    /// <summary>
    /// Json Schema definition
    /// </summary>
    public string Schema { get; private set; }

    private JSchema _schema { get; set; }

    private JSchema JSchema
    {
        get
        {
            if (_schema == null)
                _schema = JShema.Parse(Schema);

            return _schema;
        }
    }

    private void Validate(JObject obj)
    {
        // Schema validation Error messages.
        IList<string> ValidationError;

        // Schema validation.
        if (!obj.IsValid(JSchema, out ValidationError))
        {
            throw new Exception(string.Join(",", ValidationError.ToArray()));
        }
    }


    public string RunTemplate(JObject jobj)
    {
        // Validate Json Object. 
        Validate(jobj);

        // Code here that access our RazorEngine cache, and add then run Razor Template, or directly run a cached Razor Template...

        return "Here we return string generated by RazorEngine to sender.";
    }
}

Lets say i run a simple "Hello @Model.Name!" template that validates that json has string Name this is 15-20 times slower then if i comment out validation entirely.

Are there more efficient ways to use IsValid in Json.Net Schema?

like image 893
Joachim Avatar asked Jun 03 '26 11:06

Joachim


1 Answers

Make sure you update to the latest version of Json.NET Schema available on NuGet, performance was slow when validating certain schemas with older versions.

Also there is documentation on the Json.NET Schema website for performance best practices.

like image 159
James Newton-King Avatar answered Jun 06 '26 00:06

James Newton-King