• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# JSchema类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: 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);
            }

            Uri schemaId = _schemaDiscovery.KnownSchemas.Single(s => s.Schema == schema).Id;

            ValidationError error = ValidationError.CreateValidationError(message, errorType, schema, schemaId, value, childErrors, lineInfo, path);

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


示例17: Initialize

        public void Initialize(ContextBase context, Scope parent, int initialDepth, JSchema schema)
        {
            Initialize(context, parent, initialDepth, ScopeType.Object);
            InitializeSchema(schema);

            _propertyCount = 0;
            _currentPropertyName = null;

            if (!schema._required.IsNullOrEmpty())
            {
                if (_requiredProperties != null)
                {
                    _requiredProperties.Clear();
                }
                else
                {
                    _requiredProperties = new List<string>(schema._required.Count);
                }

                foreach (string required in schema._required)
                {
                    _requiredProperties.Add(required);
                }
            }

            if (!schema._dependencies.IsNullOrEmpty())
            {
                if (_readProperties != null)
                {
                    _readProperties.Clear();
                }
                else
                {
                    _readProperties = new List<string>();
                }

                if (schema._dependencies.HasSchemas)
                {
                    if (_dependencyScopes != null)
                    {
                        _dependencyScopes.Clear();
                    }
                    else
                    {
                        _dependencyScopes = new Dictionary<string, SchemaScope>(StringComparer.Ordinal);
                    }
                }
            }
        }
开发者ID:Pondidum,项目名称:Newtonsoft.Json.Schema,代码行数:49,代码来源:ObjectScope.cs


示例18: SerializeSchema

        public void SerializeSchema()
        {
            JSchema schema = new JSchema
            {
                Properties =
                {
                    { "first", new JSchema { Type = JSchemaType.String | JSchemaType.Null } }
                }
            };

            string s1 = schema.ToString();
            string s2 = JsonConvert.SerializeObject(schema, Formatting.Indented);

            Assert.AreEqual(s1, s2);
        }
开发者ID:Pondidum,项目名称:Newtonsoft.Json.Schema,代码行数:15,代码来源:SerializationTests.cs


示例19: RaiseError

        internal virtual void RaiseError(string message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors)
        {
            // mark all parent SchemaScopes as invalid
            Scope current = this;
            SchemaScope parentSchemaScope;
            while ((parentSchemaScope = current.Parent as SchemaScope) != null)
            {
                if (!parentSchemaScope.IsValid)
                    break;

                parentSchemaScope.IsValid = false;
                current = parentSchemaScope;
            }

            Context.RaiseError(message, errorType, schema, value, childErrors);
        }
开发者ID:Nangal,项目名称:Newtonsoft.Json.Schema,代码行数:16,代码来源:Scope.cs


示例20: WriteTo_ReferenceToPatternChild

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

            JSchema s = new JSchema();
            s.Id = new Uri("http://www.jnk.com/");
            s.Properties["pattern_parent"] = new JSchema
            {
                PatternProperties =
                {
                    { "///~~~test~/~/~", nested }
                }
            };
            s.Properties["ref_parent"] = new JSchema
            {
                Items =
                {
                    nested
                }
            };

            string json = s.ToString();

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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# JSchemaReader类代码示例发布时间:2022-05-24
下一篇:
C# JSToken类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap