How to validate the JSON schema in C #?

3

Follow 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: (Multiple 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 tell if the schema is from this format? Because the return code may come different from the code above json. What interests me is the json code above.

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

    
asked by anonymous 30.08.2018 / 16:10

1 answer

2

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 by being a simple object you could infer the 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 already have the class Root that represents your object.

Then you use the FromJson method of the class to convert the string that has 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 can be anything, but overall if it is a JSON object it will try to deserialize.

    
30.08.2018 / 21:09