How to validate JSON schema in C#?

Question:

Here's json (it only has 1 error, it can have several errors):

{
  "errors": [
    {
      "code": "XX-55",
      "path": "customer.id",
      "description": "Cliente não encontrado"
    }
  ]
}

Another example of the return: (Various errors)

{
  "errors": [
    {
      "code": "XD-011",
      "path": "items[0].product",
      "description": "Informe o nome do produto"
    },
    {
      "path": "items[0].quantity",
      "description": "must be between 1 and 999999"
    },
    {
      "code": "BJ-009",
      "path": "items[0].price",
      "description": "Todos os valores devem ser maiores que zero"
    }
  ]
}

How can I know if the schema is of this format? Because the return code may come different from the above json code. What interests me is the json code above.

I'm using JsonConvert.DeserializeObject to convert, but the schemma might be different. How can I know the string has this format: errors, code, path and description?

Answer:

One way is to create a deserializer using the Newtonsoft library.

The first step is to generate the classes that represent the JSON object. One way to do this is to use an online service or because it's a simple object you could infer attributes and properties. I generated this one with your example.

namespace QuickType
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class Root
    {
        [JsonProperty("errors")]
        public Error[] Errors { get; set; }
    }

    public partial class Error
    {
        [JsonProperty("code", NullValueHandling = NullValueHandling.Ignore)]
        public string Code { get; set; }

        [JsonProperty("path")]
        public string Path { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }
    }

    public partial class Root
    {
        public static Root FromJson(string json) => JsonConvert.DeserializeObject<Root>(json, QuickType.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this Root self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters = {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}

Now you have the Root class representing your object.

Then you use the FromJson method of the class to convert the string that has the JSON into an object.

var myJson = Root.FromJson("sua string com os dados do JSON");
if (myJson.Errors != null) 
{
    // Indica que o objeto foi deserializado e contem o item "Errors" no root.
}

You can increment the code to check that no Exception will occur if your input could be anything, but in general if it's a JSON object it will try to deserialize.

Scroll to Top