How to validate the JSON schema in C#?

Asked

Viewed 328 times

3

Follows json (has only 1 error, may have several errors):

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

Another example of the return: (Several 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 be different from the above json code. What interests me is the json code above.

I’m using JsonConvert.DeserializeObject to convert, but the schemma may be different. How can I know in the string has this format: errors, code, path and Description ?

  • Can you tell from the beginning schema is structured? That is, it has, somewhere in its code, the definition of schema?

  • @Joãomartins No, it just returns like this: {"errors":[{"code":"XX-55","path":"customer.id","description":"Cliente não encontrado"}]}

  • You have a library ready for this: https://www.newtonsoft.com/jsonschema

  • I just can’t make it work :/

  • Okay, this library was going to tell you to test it, but for that you have to know the structure of schema before it can validate it.

  • @Joãomartins worse than it doesn’t have, only that code above it.

  • @Joãomartins this does not serve: https://www.liquid-technologies.com/online-json-to-schema-converter ?

  • It works, but it’s a converter online. You would have to include something like this in your application. You can receive any schema? And you don’t know how many or which ones before, right?

  • @Maybe there is another way to do this without using this library, or without knowing the schema structure. Only that code above Json that returns me. I don’t know how many or which before.

Show 4 more comments

1 answer

2


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

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’ve got the class Root representing its object.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.