. NET using Jsonschema to validate JSON

Source: Internet
Author: User

  

This requirement has been encountered in recent projects and requires validation of the uploaded JSON to ensure the accuracy of the JSON data. There are two ways to verify it before and after:

 

(1) The realization of the first way: according to the format of the JSON data, the corresponding class structure is strictly defined, and in the System.Runtime.Serialization namespace DataContractAttribute, DataMemberAttribute the class and property, and if the property is mandatory, add [DataMember (IsRequired = True)] to the property.

Then use the Jsonconvert.deserializeobject<t> () method in the Newtonsoft.json assembly to deserialize it with the jsoncontent that needs validation and try ... The catch contains the deserialization statement, and if the conversion succeeds, it indicates that the jsoncontent format satisfies the requirement. If the conversion is unsuccessful, an exception is thrown and a catch is caught.

  

  

            Try            {                var obj = jsonconvert.deserializeobject<skuconfigentity> (skumanifest, new Jsonserializersettings ()                {                    formatting = formatting.indented,                    nullvaluehandling = Nullvaluehandling.ignore,                    missingmemberhandling = Missingmemberhandling.error                });            }            catch (Exception e)            {                return false;            }

  

This method is the initial use of the method, the individual is not perfect, is not perfect, conversion error situation Plus, exception can not give a specific cause of the error.

(2) The second realization idea: JSON schema (JSON schema). Under the guidance of my predecessors, I know the JSON Schema,

JSON mode is a specification that defines JSON data structures based on JSON format. It was written under the IETF draft and expired in 2011. JSON mode:

    • Describes the existing data format.
    • Clean human and machine readable documentation.
    • Complete structural validation facilitates automated testing.
    • Complete structural validation that can be used to validate the data submitted by the client.
JSON Schema Validation Library

There are currently several validators available for different programming languages. But currently the most complete and compatible JSON-mode validator is JSV.

language Program Library
C Wjelement (LGPLV3)
Java Json-schema-validator (LGPLV3)
. NET Json.NET (MIT)
ActionScript 3 Frigga (MIT)
Haskell Aeson-schema (MIT)
Python Jsonschema
Ruby Autoparse (ASL 2.0); Ruby-jsonschema (MIT)
Php Php-json-schema (MIT). Json-schema (Berkeley)
Javascript Orderly (BSD); JSV; Json-schema; Matic (MIT); Dojo; Persevere (modified BSD or AFL 2.0); Schema.js.

   

 

JSON Pattern Example

The following is a basic JSON pattern that covers a classic product catalog description:

{    "$schema": "http://json-schema.org/draft-04/schema#",    "title": "Product",    "description": "A product from Acme‘s catalog",    "type": "object",    "properties": {        "id": {            "description": "The unique identifier for a product",            "type": "integer"        },        "name": {            "description": "Name of the product",            "type": "string"        },        "price": {            "type": "number",            "minimum": 0,            "exclusiveMinimum": true        }    },    "required": ["id", "name", "price"]}

Let's take a look at the various important keywords that can be used in this pattern:

Key Words Description
$schema $schema the keyword state, indicating that this pattern is consistent with the draft V4 specification.
Title It gives us the title of the pattern.
Description A description of the pattern.
Type The Type keyword defines the first constraint on our JSON data: it must be a JSON object.
Properties Defines the various keys and their value types, as well as the minimum and maximum values used in the JSON file.
Required The list of required attributes is stored.
Minimum A constraint set on a value that represents the minimum value that can be accepted.
Exclusiveminimum If "Exclusiveminimum" is present and has a Boolean value of true, the instance is valid if it is strictly greater than the value of "minimum".
Maximum A constraint set on a value that represents the maximum value that can be accepted.
Exclusivemaximum If "Exclusiveminimum" is present and has a Boolean value of true, the instance is valid if it is strictly less than the value of "maximum".
Multipleof If the result of splitting an instance through the value of this keyword is a number, then a numeric instance that is immediately adjacent to "multipleof" is valid.
MaxLength The maximum length value of the string instance character.
MinLength The minimum length value of the string instance character.
Pattern If the regular expression matches the instance successfully, the string instance is considered valid.

The JSON pattern described above can be used to verify the following JSON string.

[    {        "id": 2,        "name": "An ice sculpture",        "price": 12.50    },    {        "id": 3,        "name": "A Blue Mouse ",        " price ": 25.50    }]


In. NET, the Json Schema can be implemented through the Jsonschema class under the Newtonsoft.Json.Schema namespace.

Each Jsonschema instance represents the description and restrictions of a property.

Several key attributes of the Jsonschema class:

Type Set the type of the property
Required Sets whether the property is required
Properties Contains all the next-level properties of the Jsonschema, which is the dictionary<string,jsonschema> type, to be initialized before the child is added.
Items Contains the jsonschema of all the next-level array items, which are ilist<jsonschema> types that need to be initialized before the child is added.

Using the IsValid () extension method under the Newtonsoft.Json.Schema namespace enables validation of the Json string, which is an extension of the Jtoken.

public static Jsonschema Getskujsonschema ()
{

            Jsonschema rootschema = new Jsonschema () {Title = "Sku.json", Type = Jso Nschematype.object};

            Rootschema.properties = new dictionary<string, jsonschema> ();            ROOTSCHEMA.PROPERTIES.ADD ("name", new Jsonschema () {Type = jsonschematype.string, Required = true});            ROOTSCHEMA.PROPERTIES.ADD ("DisplayName", new Jsonschema () {Type = jsonschematype.string, Required = true});            ROOTSCHEMA.PROPERTIES.ADD ("Apiminstance", new Jsonschema () {Type = jsonschematype.string, Required = true});            ROOTSCHEMA.PROPERTIES.ADD ("Apipath", new Jsonschema () {Type = jsonschematype.string, Required = true});            Jsonschema Skuschema = new Jsonschema () {Title = "SKUs", Type = Jsonschematype.array, Required = true};            skuschema.properties= New dictionary<string, jsonschema> ();            SKUSCHEMA.PROPERTIES.ADD ("name", new Jsonschema () {Type = jsonschematype.string, Required = true});            SKUSCHEMA.PROPERTIES.ADD ("Tier", new Jsonschema () {Type = jsonschematype.string, Required = true}); Skuschema.propeRties.            ADD ("Subscriptionskuquota", new Jsonschema () {Type = Jsonschematype.integer, Required = false});            SKUSCHEMA.PROPERTIES.ADD ("Skutype", new Jsonschema () {Type = jsonschematype.string, Required = false});            SKUSCHEMA.PROPERTIES.ADD ("Skuquota", new Jsonschema () {Type = jsonschematype.string, Required = false});            SKUSCHEMA.PROPERTIES.ADD ("Apimproductid", new Jsonschema () {Type = jsonschematype.string, Required = false});            Jsonschema Locationsschema = new Jsonschema () {Title = "locations", Type = Jsonschematype.array, Required = true};            locationsschema.properties= New dictionary<string, jsonschema> ();            LOCATIONSSCHEMA.PROPERTIES.ADD ("Location", new Jsonschema () {Type = jsonschematype.string, Required = true});            LOCATIONSSCHEMA.PROPERTIES.ADD ("Apimproductid", new Jsonschema () {Type = jsonschematype.string, Required = false});        SKUSCHEMA.PROPERTIES.ADD ("Locations", Locationsschema);    Jsonschema Meteridsschema = new Jsonschema () {Title = "Meterids", Type = Jsonschematype.array, Required = true};            Meteridsschema.items = new list<jsonschema> ();            METERIDSSCHEMA.ITEMS.ADD (New Jsonschema () {Type = jsonschematype.string, Required = false});            SKUSCHEMA.PROPERTIES.ADD ("Meterids", Meteridsschema);  Jsonschema Requiredfeaturesschema = new Jsonschema () {Title = "requiredfeatures", Type = Jsonschematype.array, Required =            True};            Requiredfeaturesschema.items = new list<jsonschema> ();            REQUIREDFEATURESSCHEMA.ITEMS.ADD (New Jsonschema () {Type = jsonschematype.string, Required = false});            SKUSCHEMA.PROPERTIES.ADD ("Requiredfeatures", Requiredfeaturesschema);            ROOTSCHEMA.PROPERTIES.ADD ("SKUs", Skuschema); return rootschema;
}

  

Jtoken Jtoken=jtoken.parse (jsoncontent);

Ilist<string> errorlist;

var result=jtoken. IsValid (schema, out errorlist);

If the validation succeeds, Ture is returned, false if the validation fails, and the errorlist contains detailed error information.

. NET using Jsonschema to validate JSON

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.