当前位置: 首页>>代码示例>>C#>>正文


C# JSchema类代码示例

本文整理汇总了C#中JSchema的典型用法代码示例。如果您正苦于以下问题:C# JSchema类的具体用法?C# JSchema怎么用?C# JSchema使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


JSchema类属于命名空间,在下文中一共展示了JSchema类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: RaiseError

        public override void RaiseError(string message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors)
        {
            if (Errors == null)
                Errors = new List<ValidationError>();

            Errors.Add(Validator.CreateError(message, errorType, schema, value, childErrors));
        }
开发者ID:Nangal,项目名称:Newtonsoft.Json.Schema,代码行数:7,代码来源:ConditionalContext.cs

示例2: RaiseError

        public void RaiseError(IFormattable message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors)
        {
            ValidationError error = CreateError(message, errorType, schema, value, childErrors);

            // shared cache information that could be read/populated from multiple threads
            // lock to ensure that only one thread writes known schemas
            if (Schema.KnownSchemas.Count == 0)
            {
                lock (Schema.KnownSchemas)
                {
                    if (Schema.KnownSchemas.Count == 0)
                    {
                        JSchemaDiscovery discovery = new JSchemaDiscovery(Schema.KnownSchemas, KnownSchemaState.External);
                        discovery.Discover(Schema, null);
                    }
                }
            }

            PopulateSchemaId(error);

            SchemaValidationEventHandler handler = ValidationEventHandler;
            if (handler != null)
                handler(_publicValidator, new SchemaValidationEventArgs(error));
            else
                throw JSchemaValidationException.Create(error);
        }
开发者ID:bmperdue,项目名称:Newtonsoft.Json.Schema,代码行数:26,代码来源:Validator.cs

示例3: WriteTo_ReferenceWithRootId

        public void WriteTo_ReferenceWithRootId()
        {
            JSchema nested = new JSchema
            {
                Type = JSchemaType.Object
            };

            JSchema s = new JSchema();
            s.Id = new Uri("http://www.jnk.com/");
            s.Items.Add(nested);
            s.Properties["test"] = nested;

            string json = s.ToString();

            StringAssert.AreEqual(@"{
  ""id"": ""http://www.jnk.com/"",
  ""properties"": {
    ""test"": {
      ""type"": ""object""
    }
  },
  ""items"": {
    ""$ref"": ""#/properties/test""
  }
}", json);
        }
开发者ID:bmperdue,项目名称:Newtonsoft.Json.Schema,代码行数:26,代码来源:JSchemaWriterTests.cs

示例4: CreateError

        protected ValidationError CreateError(string message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors, IJsonLineInfo lineInfo, string path)
        {
            if (_schemaDiscovery == null)
            {
                _schemaDiscovery = new JSchemaDiscovery();
                _schemaDiscovery.Discover(Schema, null);
            }

            ValidationError error = new ValidationError();
            error.Message = message;
            error.ErrorType = errorType;
            error.Path = path;
            if (lineInfo != null)
            {
                error.LineNumber = lineInfo.LineNumber;
                error.LinePosition = lineInfo.LinePosition;
            }
            error.Schema = schema;
            error.SchemaId = _schemaDiscovery.KnownSchemas.Single(s => s.Schema == schema).Id;
            error.SchemaBaseUri = schema.BaseUri;
            error.Value = value;
            error.ChildErrors = childErrors;

            return error;
        }
开发者ID:Nangal,项目名称:Newtonsoft.Json.Schema,代码行数:25,代码来源:Validator.cs

示例5: ArrayBasicValidation_Pass

        public void ArrayBasicValidation_Pass()
        {
            JSchema schema = new JSchema();
            schema.Type = JSchemaType.Array;
            schema.Items.Add(new JSchema
            {
                Type = JSchemaType.Integer
            });

            SchemaValidationEventArgs a = null;

            StringWriter sw = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(sw);
            JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer);
            validatingWriter.Schema = schema;
            validatingWriter.ValidationEventHandler += (sender, args) => { a = args; };

            validatingWriter.WriteStartArray();
            validatingWriter.WriteValue(10);
            validatingWriter.WriteValue(10);
            validatingWriter.WriteEndArray();

            Assert.IsNull(a);

            Assert.AreEqual("[10,10]", sw.ToString());
        }
开发者ID:Pondidum,项目名称:Newtonsoft.Json.Schema,代码行数:26,代码来源:JSchemaValidatingWriterTests.cs

示例6: GetSchema

        /// <summary>
        /// Gets a <see cref="JSchema"/> for a <see cref="Type"/>.
        /// </summary>
        /// <param name="context">The <see cref="Type"/> and associated information used to generate a <see cref="JSchema"/>.</param>
        /// <returns>The generated <see cref="JSchema"/>.</returns>
        public override JSchema GetSchema(JSchemaTypeGenerationContext context)
        {
            bool isNullable = ReflectionUtils.IsNullableType(context.ObjectType);
            Type t = isNullable ? Nullable.GetUnderlyingType(context.ObjectType) : context.ObjectType;

            if (!t.IsEnum())
            {
                return null;
            }

            JSchema schema = new JSchema
            {
                Type = JSchemaType.String
            };

            if (isNullable && context.Required != Required.Always)
            {
                schema.Type |= JSchemaType.Null;
            }

            string[] names = Enum.GetNames(t);

            foreach (string name in names)
            {
                string finalName = EnumUtils.ToEnumName(t, name, CamelCaseText);

                schema.Enum.Add(JValue.CreateString(finalName));
            }

            return schema;
        }
开发者ID:Pondidum,项目名称:Newtonsoft.Json.Schema,代码行数:36,代码来源:StringEnumGenerationProvider.cs

示例7: DiscoverInternal

        private void DiscoverInternal(JSchema schema, string latestPath)
        {
            if (schema.Reference != null)
                return;

            if (_knownSchemas.Any(s => s.Schema == schema))
                return;

            Uri newScopeId;
            Uri schemaKnownId = GetSchemaIdAndNewScopeId(schema, ref latestPath, out newScopeId);

            // check whether a schema with the resolved id is already known
            // this will be hit when a schema contains duplicate ids or references a schema with a duplicate id
            bool existingSchema = _knownSchemas.Any(s => UriComparer.Instance.Equals(s.Id, schemaKnownId));

#if DEBUG
            if (_knownSchemas.Any(s => s.Schema == schema))
                throw new InvalidOperationException("Schema with id '{0}' already a known schema.".FormatWith(CultureInfo.InvariantCulture, schemaKnownId));
#endif

            // add schema to known schemas whether duplicate or not to avoid multiple errors
            // the first schema with a duplicate id will be used
            _knownSchemas.Add(new KnownSchema(schemaKnownId, schema, _state));

            if (existingSchema)
            {
                if (ValidationErrors != null)
                {
                    ValidationError error = ValidationError.CreateValidationError("Duplicate schema id '{0}' encountered.".FormatWith(CultureInfo.InvariantCulture, schemaKnownId.OriginalString), ErrorType.Id, schema, null, schemaKnownId, null, schema, schema.Path);
                    ValidationErrors.Add(error);
                }

                return;
            }

            _pathStack.Push(new SchemaPath(newScopeId, latestPath));

            // discover should happen in the same order as writer except extension data (e.g. definitions)
            if (schema._extensionData != null)
            {
                foreach (KeyValuePair<string, JToken> valuePair in schema._extensionData)
                {
                    DiscoverTokenSchemas(EscapePath(valuePair.Key), valuePair.Value);
                }
            }

            DiscoverSchema(Constants.PropertyNames.AdditionalProperties, schema.AdditionalProperties);
            DiscoverSchema(Constants.PropertyNames.AdditionalItems, schema.AdditionalItems);
            DiscoverDictionarySchemas(Constants.PropertyNames.Properties, schema._properties);
            DiscoverDictionarySchemas(Constants.PropertyNames.PatternProperties, schema._patternProperties);
            DiscoverDictionarySchemas(Constants.PropertyNames.Dependencies, schema._dependencies);
            DiscoverArraySchemas(Constants.PropertyNames.Items, schema._items);
            DiscoverArraySchemas(Constants.PropertyNames.AllOf, schema._allOf);
            DiscoverArraySchemas(Constants.PropertyNames.AnyOf, schema._anyOf);
            DiscoverArraySchemas(Constants.PropertyNames.OneOf, schema._oneOf);
            DiscoverSchema(Constants.PropertyNames.Not, schema.Not);

            _pathStack.Pop();
        }
开发者ID:TheRomeroAgency,项目名称:Newtonsoft.Json.Schema,代码行数:59,代码来源:JSchemaDiscovery.cs

示例8: CreateTokenScope

        public static SchemaScope CreateTokenScope(JsonToken token, JSchema schema, ContextBase context, Scope parent, int depth)
        {
            SchemaScope scope;

            switch (token)
            {
                case JsonToken.StartObject:
                    var objectScope = new ObjectScope(context, parent, depth, schema);
                    context.Scopes.Add(objectScope);

                    objectScope.InitializeScopes(token);

                    scope = objectScope;
                    break;
                case JsonToken.StartArray:
                case JsonToken.StartConstructor:
                    scope = new ArrayScope(context, parent, depth, schema);
                    context.Scopes.Add(scope);
                    break;
                default:
                    scope = new PrimativeScope(context, parent, depth, schema);
                    context.Scopes.Add(scope);
                    break;
            }

            if (schema._allOf != null && schema._allOf.Count > 0)
            {
                AllOfScope allOfScope = new AllOfScope(scope, context, depth);
                context.Scopes.Add(allOfScope);

                allOfScope.InitializeScopes(token, schema._allOf);
            }
            if (schema._anyOf != null && schema._anyOf.Count > 0)
            {
                AnyOfScope anyOfScope = new AnyOfScope(scope, context, depth);
                context.Scopes.Add(anyOfScope);

                anyOfScope.InitializeScopes(token, schema._anyOf);
            }
            if (schema._oneOf != null && schema._oneOf.Count > 0)
            {
                OneOfScope oneOfScope = new OneOfScope(scope, context, depth);
                context.Scopes.Add(oneOfScope);

                oneOfScope.InitializeScopes(token, schema._oneOf);
            }
            if (schema.Not != null)
            {
                NotScope notScope = new NotScope(scope, context, depth);
                context.Scopes.Add(notScope);

                notScope.InitializeScopes(token, Enumerable.Repeat(schema.Not, 1));
            }

            return scope;
        }
开发者ID:bmperdue,项目名称:Newtonsoft.Json.Schema,代码行数:56,代码来源:SchemaScope.cs

示例9: Discover

        public void Discover(JSchema schema, Uri uri, string path = "#")
        {
            Uri resolvedUri = uri ?? schema.Id ?? new Uri(string.Empty, UriKind.RelativeOrAbsolute);

            _pathStack.Push(new SchemaPath(resolvedUri, string.Empty));

            DiscoverInternal(schema, path);

            _pathStack.Pop();
        }
开发者ID:TheRomeroAgency,项目名称:Newtonsoft.Json.Schema,代码行数:10,代码来源:JSchemaDiscovery.cs

示例10: RaiseError

        public void RaiseError(string message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors)
        {
            ValidationError error = CreateError(message, errorType, schema, value, childErrors);

            SchemaValidationEventHandler handler = ValidationEventHandler;
            if (handler != null)
                handler(_publicValidator, new SchemaValidationEventArgs(error));
            else
                throw JSchemaValidationException.Create(error);
        }
开发者ID:Nangal,项目名称:Newtonsoft.Json.Schema,代码行数:10,代码来源:Validator.cs

示例11: SetResolvedSchema

        public void SetResolvedSchema(JSchema schema)
        {
            foreach (Action<JSchema> setSchema in SetSchemas)
            {
                setSchema(schema);
            }

            // successful
            _success = (schema.Reference == null);
        }
开发者ID:Pondidum,项目名称:Newtonsoft.Json.Schema,代码行数:10,代码来源:DeferedSchema.cs

示例12: WriteTo_MaximumLength_Large

        public void WriteTo_MaximumLength_Large()
        {
            JSchema s = new JSchema
            {
                MaximumLength = long.MaxValue
            };

            string json = s.ToString();

            StringAssert.AreEqual(@"{
  ""maxLength"": 9223372036854775807
}", json);
        }
开发者ID:bmperdue,项目名称:Newtonsoft.Json.Schema,代码行数:13,代码来源:JSchemaWriterTests.cs

示例13: WriteTo_UniqueItems

        public void WriteTo_UniqueItems()
        {
            JSchema s = new JSchema
            {
                UniqueItems = true
            };

            string json = s.ToString();

            StringAssert.AreEqual(@"{
  ""uniqueItems"": true
}", json);
        }
开发者ID:bmperdue,项目名称:Newtonsoft.Json.Schema,代码行数:13,代码来源:JSchemaWriterTests.cs

示例14: ObjectScope

        public ObjectScope(ContextBase context, Scope parent, int initialDepth, JSchema schema)
            : base(context, parent, initialDepth, schema)
        {
            if (schema._required != null)
                _requiredProperties = schema._required.ToList();

            if (schema._dependencies != null && schema._dependencies.Count > 0)
            {
                _readProperties = new List<string>();

                if (schema._dependencies.Values.OfType<JSchema>().Any())
                    _dependencyScopes = new Dictionary<string, SchemaScope>();
            }
        }
开发者ID:Nangal,项目名称:Newtonsoft.Json.Schema,代码行数:14,代码来源:ObjectScope.cs

示例15: Example

        public void Example()
        {
            #region Usage
            JSchema schema = new JSchema
            {
                Type = JSchemaType.Object,
                Properties =
                {
                    { "name", new JSchema { Type = JSchemaType.String } },
                    {
                        "hobbies", new JSchema
                        {
                            Type = JSchemaType.Array,
                            Items = { new JSchema { Type = JSchemaType.String } }
                        }
                    },
                }
            };

            string schemaJson = schema.ToString();

            Console.WriteLine(schemaJson);
            // {
            //   "type": "object",
            //   "properties": {
            //     "name": {
            //       "type": "string"
            //     },
            //     "hobbies": {
            //       "type": "array",
            //       "items": {
            //         "type": "string"
            //       }
            //     }
            //   }
            // }

            JObject person = JObject.Parse(@"{
              'name': 'James',
              'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
            }");

            bool valid = person.IsValid(schema);

            Console.WriteLine(valid);
            // true
            #endregion

            Assert.IsTrue(valid);
        }
开发者ID:Pondidum,项目名称:Newtonsoft.Json.Schema,代码行数:50,代码来源:CreateJsonSchemaManually.cs


注:本文中的JSchema类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。