public WeatherSuggestion(JsonContract.WeatherSuggestionContract suggestion) { if (suggestion == null) { return; } Comfortable = new Suggestion(suggestion.comf); CarWashing = new Suggestion(suggestion.cw); Dressing = new Suggestion(suggestion.drsg); Flu = new Suggestion(suggestion.flu); Sport = new Suggestion(suggestion.sport); UV = new Suggestion(suggestion.uv); Trav = new Suggestion(suggestion.trav); }
public HourlyForecast(JsonContract.HourlyForecastContract hourly_forecast) { if (hourly_forecast == null) { return; } CultureInfo provider = CultureInfo.InvariantCulture; DateTime = DateTime.ParseExact(hourly_forecast.date, "yyyy-MM-dd HH:mm", provider); Humidity = uint.Parse(hourly_forecast.hum); Pop = uint.Parse(hourly_forecast.pop); Pressure = Pressure.FromHPa(float.Parse(hourly_forecast.pres, provider)); Temprature = Temperature.FromCelsius(int.Parse(hourly_forecast.tmp)); Wind = new Wind(hourly_forecast.wind); }
public Location(JsonContract.LocationContract basic) { if (basic == null) { return; } CultureInfo provider = CultureInfo.InvariantCulture; City = basic.city; Country = basic.cnty; CityId = basic.id; Latitude = float.Parse(basic.lat, provider); Longitude = float.Parse(basic.lon, provider); UpdateTime = DateTime.ParseExact(basic.update.loc, "yyyy-MM-dd H:mm", provider); UtcTime = DateTime.ParseExact(basic.update.utc, "yyyy-MM-dd H:mm", provider); }
public WeatherAlarm(JsonContract.WeatherAlarmContract alarm) { if (alarm == null) { return; } try { Level = ParseLevel(alarm.level); Type = ParseType(alarm.type); Title = alarm.title; Text = alarm.txt; } catch (Exception) { return; } }
public DailyForecast(JsonContract.DailyForecastContract daily_forecast) { if (daily_forecast == null) { return; } CultureInfo provider = CultureInfo.InvariantCulture; Date = DateTime.ParseExact(daily_forecast.date, "yyyy-MM-dd", provider); SunRise = TimeSpan.Parse(daily_forecast.astro.sr); SunSet = TimeSpan.Parse(daily_forecast.astro.ss); Condition = new DailyCondition(daily_forecast.cond); Humidity = uint.Parse(daily_forecast.hum); Precipitation = float.Parse(daily_forecast.pcpn, provider); Pop = uint.Parse(daily_forecast.pop); Pressure = Pressure.FromHPa(float.Parse(daily_forecast.pres, provider)); HighTemp = Temperature.FromCelsius(int.Parse(daily_forecast.tmp.max)); LowTemp = Temperature.FromCelsius(int.Parse(daily_forecast.tmp.min)); Visibility = Length.FromKM(float.Parse(daily_forecast.vis, provider)); Wind = new Wind(daily_forecast.wind); }
public NowWeather(JsonContract.NowWeatherContract now) { if (now == null) { return; } CultureInfo provider = CultureInfo.InvariantCulture; Now = new NowCondition(now.cond); int fl; if (int.TryParse(now.fl, NumberStyles.Any, provider, out fl)) BodyTemprature = Temperature.FromCelsius(fl); float pcpn; if (float.TryParse(now.pcpn, NumberStyles.Any, provider, out pcpn)) Precipitation = pcpn; if (float.TryParse(now.vis, NumberStyles.Any, provider, out pcpn)) Visibility = Length.FromKM(pcpn); Wind = new Wind(now.wind); if (float.TryParse(now.pres, NumberStyles.Any, provider, out pcpn)) Pressure = Pressure.FromHPa(pcpn); if (int.TryParse(now.tmp, NumberStyles.Any, provider, out fl)) Temprature = Temperature.FromCelsius(fl); }
public override object PopulateMember(string memberName, JsonContract contract, JsonReader reader, Type objectType, object targetObject, JsonSerializerReader internalReader) { if (objectType == typeof(Vector2)) { Vector2 vector = (Vector2)targetObject; switch (memberName) { case "x": vector.x = (float)reader.ReadAsDecimal(); break; case "y": vector.y = (float)reader.ReadAsDecimal(); break; default: reader.Skip(); break; } return(vector); } else if (objectType == typeof(Vector3)) { Vector3 vector = (Vector3)targetObject; switch (memberName) { case "x": vector.x = (float)reader.ReadAsDecimal(); break; case "y": vector.y = (float)reader.ReadAsDecimal(); break; case "z": vector.z = (float)reader.ReadAsDecimal(); break; default: reader.Skip(); break; } return(vector); } else if (objectType == typeof(Vector4)) { Vector4 vector = (Vector4)targetObject; switch (memberName) { case "x": vector.x = (float)reader.ReadAsDecimal(); break; case "y": vector.y = (float)reader.ReadAsDecimal(); break; case "z": vector.z = (float)reader.ReadAsDecimal(); break; case "w": vector.w = (float)reader.ReadAsDecimal(); break; default: reader.Skip(); break; } return(vector); } #if UNITY_2017_2_OR_NEWER else if (objectType == typeof(Vector2Int)) { Vector2Int vector = (Vector2Int)targetObject; switch (memberName) { case "x": vector.x = reader.ReadAsInt32().GetValueOrDefault(); break; case "y": vector.y = reader.ReadAsInt32().GetValueOrDefault(); break; default: reader.Skip(); break; } return(vector); } else if (objectType == typeof(Vector3Int)) { Vector3Int vector = (Vector3Int)targetObject; switch (memberName) { case "x": vector.x = reader.ReadAsInt32().GetValueOrDefault(); break; case "y": vector.y = reader.ReadAsInt32().GetValueOrDefault(); break; case "z": vector.z = reader.ReadAsInt32().GetValueOrDefault(); break; default: reader.Skip(); break; } return(vector); } #endif return(targetObject); }
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { JsonConverter converter; ValidationUtils.ArgumentNotNull(type, "type"); string typeId = this.GetTypeId(type, false); string str2 = this.GetTypeId(type, true); if (!string.IsNullOrEmpty(typeId)) { JsonSchema schema = this._resolver.GetSchema(typeId); if (schema != null) { if ((valueRequired != Required.Always) && !HasFlag(schema.Type, JsonSchemaType.Null)) { schema.Type = ((JsonSchemaType)schema.Type) | JsonSchemaType.Null; } if (required) { bool?nullable3 = schema.Required; bool flag = true; if ((nullable3.GetValueOrDefault() == flag) ? !nullable3.HasValue : true) { schema.Required = true; } } return(schema); } } if (this._stack.Any <TypeSchema>(tc => tc.Type == type)) { throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); } JsonContract contract = this.ContractResolver.ResolveContract(type); if (((converter = contract.Converter) != null) || ((converter = contract.InternalConverter) != null)) { JsonSchema schema = converter.GetSchema(); if (schema != null) { return(schema); } } this.Push(new TypeSchema(type, new JsonSchema())); if (str2 != null) { this.CurrentSchema.Id = str2; } if (required) { this.CurrentSchema.Required = true; } this.CurrentSchema.Title = this.GetTitle(type); this.CurrentSchema.Description = this.GetDescription(type); if (converter != null) { this.CurrentSchema.Type = 0x7f; } else { switch (contract.ContractType) { case JsonContractType.Object: this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); this.GenerateObjectSchema(type, (JsonObjectContract)contract); goto Label_0516; case JsonContractType.Array: { this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Array, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); JsonArrayAttribute cachedAttribute = JsonTypeReflector.GetCachedAttribute <JsonArrayAttribute>(type); bool flag2 = (cachedAttribute == null) || cachedAttribute.AllowNullItems; Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { this.CurrentSchema.Items = new List <JsonSchema>(); this.CurrentSchema.Items.Add(this.GenerateInternal(collectionItemType, !flag2 ? Required.Always : Required.Default, false)); } goto Label_0516; } case JsonContractType.Primitive: { this.CurrentSchema.Type = new JsonSchemaType?(this.GetJsonSchemaType(type, valueRequired)); JsonSchemaType?nullable = this.CurrentSchema.Type; JsonSchemaType integer = JsonSchemaType.Integer; if ((!((((JsonSchemaType)nullable.GetValueOrDefault()) == integer) ? nullable.HasValue : false) || !type.IsEnum()) || type.IsDefined(typeof(FlagsAttribute), true)) { goto Label_0516; } this.CurrentSchema.Enum = new List <JToken>(); using (IEnumerator <EnumValue <long> > enumerator = EnumUtils.GetNamesAndValues <long>(type).GetEnumerator()) { while (enumerator.MoveNext()) { JToken item = JToken.FromObject(enumerator.Current.Value); this.CurrentSchema.Enum.Add(item); } goto Label_0516; } } case JsonContractType.String: { JsonSchemaType type5 = !ReflectionUtils.IsNullable(contract.UnderlyingType) ? JsonSchemaType.String : this.AddNullType(JsonSchemaType.String, valueRequired); this.CurrentSchema.Type = new JsonSchemaType?(type5); goto Label_0516; } case JsonContractType.Dictionary: this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); ReflectionUtils.GetDictionaryKeyValueTypes(type, out Type type6, out Type type7); if ((type6 != null) && (this.ContractResolver.ResolveContract(type6).ContractType == JsonContractType.Primitive)) { this.CurrentSchema.AdditionalProperties = this.GenerateInternal(type7, Required.Default, false); } goto Label_0516; case JsonContractType.Dynamic: case JsonContractType.Linq: this.CurrentSchema.Type = 0x7f; goto Label_0516; case JsonContractType.Serializable: this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); this.GenerateISerializableContract(type, (JsonISerializableContract)contract); goto Label_0516; } throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } Label_0516: return(this.Pop().Schema); }
protected override bool CanGenerateSchemaFor(ModelMetadata modelMetadata, JsonContract jsonContract) { return(SchemaGeneratorOptions.SubTypesResolver(modelMetadata.ModelType).Any()); }
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { ValidationUtils.ArgumentNotNull(type, "type"); string typeId = GetTypeId(type, explicitOnly: false); string typeId2 = GetTypeId(type, explicitOnly: true); if (!string.IsNullOrEmpty(typeId)) { JsonSchema schema = _resolver.GetSchema(typeId); if (schema != null) { if (valueRequired != Required.Always && !HasFlag(schema.Type, JsonSchemaType.Null)) { schema.Type |= JsonSchemaType.Null; } if (required && schema.Required != true) { schema.Required = true; } return(schema); } } if (_stack.Any((TypeSchema tc) => tc.Type == type)) { throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); } JsonContract jsonContract = ContractResolver.ResolveContract(type); JsonConverter jsonConverter; if ((jsonConverter = jsonContract.Converter) != null || (jsonConverter = jsonContract.InternalConverter) != null) { JsonSchema schema2 = jsonConverter.GetSchema(); if (schema2 != null) { return(schema2); } } Push(new TypeSchema(type, new JsonSchema())); if (typeId2 != null) { CurrentSchema.Id = typeId2; } if (required) { CurrentSchema.Required = true; } CurrentSchema.Title = GetTitle(type); CurrentSchema.Description = GetDescription(type); if (jsonConverter != null) { CurrentSchema.Type = JsonSchemaType.Any; } else if (jsonContract is JsonDictionaryContract) { CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); ReflectionUtils.GetDictionaryKeyValueTypes(type, out var keyType, out var valueType); if (keyType != null && typeof(IConvertible).IsAssignableFrom(keyType)) { CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, required: false); } } else if (jsonContract is JsonArrayContract) { CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired); CurrentSchema.Id = GetTypeId(type, explicitOnly: false); bool flag = (JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute)?.AllowNullItems ?? true; Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { CurrentSchema.Items = new List <JsonSchema>(); CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!flag) ? Required.Always : Required.Default, required: false)); } } else if (jsonContract is JsonPrimitiveContract) { CurrentSchema.Type = GetJsonSchemaType(type, valueRequired); if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum && !type.IsDefined(typeof(FlagsAttribute), inherit: true)) { CurrentSchema.Enum = new List <JToken>(); CurrentSchema.Options = new Dictionary <JToken, string>(); EnumValues <long> namesAndValues = EnumUtils.GetNamesAndValues <long>(type); foreach (EnumValue <long> item in namesAndValues) { JToken jToken = JToken.FromObject(item.Value); CurrentSchema.Enum.Add(jToken); CurrentSchema.Options.Add(jToken, item.Name); } } } else if (jsonContract is JsonObjectContract) { CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, explicitOnly: false); GenerateObjectSchema(type, (JsonObjectContract)jsonContract); } else if (jsonContract is JsonISerializableContract) { CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, explicitOnly: false); GenerateISerializableContract(type, (JsonISerializableContract)jsonContract); } else if (jsonContract is JsonStringContract) { JsonSchemaType value = ((!ReflectionUtils.IsNullable(jsonContract.UnderlyingType)) ? JsonSchemaType.String : AddNullType(JsonSchemaType.String, valueRequired)); CurrentSchema.Type = value; } else { if (!(jsonContract is JsonLinqContract)) { throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContract)); } CurrentSchema.Type = JsonSchemaType.Any; } return(Pop().Schema); }
private void PopulateSchema(JSchema schema, JsonContract contract, JsonProperty memberProperty, Required valueRequired) { schema.Title = GetTitle(contract.NonNullableUnderlyingType); schema.Description = GetDescription(contract.NonNullableUnderlyingType); JsonConverter converter = contract.Converter ?? contract.InternalConverter; if (converter != null) { schema.Type = null; } else { switch (contract.ContractType) { case JsonContractType.Object: if (schema.Id == null) { schema.Id = GetTypeId(contract.NonNullableUnderlyingType, false); } schema.Type = AddNullType(JSchemaType.Object, valueRequired); GenerateObjectSchema(schema, contract.NonNullableUnderlyingType, (JsonObjectContract)contract); break; case JsonContractType.Array: if (schema.Id == null) { schema.Id = GetTypeId(contract.NonNullableUnderlyingType, false); } schema.Type = AddNullType(JSchemaType.Array, valueRequired); schema.MinimumItems = DataAnnotationHelpers.GetMinLength(memberProperty); schema.MaximumItems = DataAnnotationHelpers.GetMaxLength(memberProperty); JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetCachedAttribute <JsonArrayAttribute>(contract.NonNullableUnderlyingType); Required?required = null; if (arrayAttribute != null && !arrayAttribute.AllowNullItems) { required = Required.Always; } Type collectionItemType = ReflectionUtils.GetCollectionItemType(contract.NonNullableUnderlyingType); if (collectionItemType != null) { schema.Items.Add(GenerateInternal(collectionItemType, required, null, (JsonArrayContract)contract, null)); } break; case JsonContractType.Primitive: schema.Type = GetJSchemaType(contract.UnderlyingType, valueRequired); if (JSchemaTypeHelpers.HasFlag(schema.Type, JSchemaType.String)) { int minimumLength; int maximumLength; if (DataAnnotationHelpers.GetStringLength(memberProperty, out minimumLength, out maximumLength)) { schema.MinimumLength = minimumLength; schema.MaximumLength = maximumLength; } else { schema.MinimumLength = DataAnnotationHelpers.GetMinLength(memberProperty); schema.MaximumLength = DataAnnotationHelpers.GetMaxLength(memberProperty); } schema.Pattern = DataAnnotationHelpers.GetPattern(memberProperty); schema.Format = DataAnnotationHelpers.GetFormat(memberProperty); } if (JSchemaTypeHelpers.HasFlag(schema.Type, JSchemaType.Number) || JSchemaTypeHelpers.HasFlag(schema.Type, JSchemaType.Integer)) { double minimum; double maximum; if (DataAnnotationHelpers.GetRange(memberProperty, out minimum, out maximum)) { schema.Minimum = minimum; schema.Maximum = maximum; } } if (JSchemaTypeHelpers.HasFlag(schema.Type, JSchemaType.Integer) && contract.NonNullableUnderlyingType.IsEnum() && ReflectionUtils.GetAttribute <FlagsAttribute>(contract.NonNullableUnderlyingType) == null) { if ((schema.Type & JSchemaType.Null) == JSchemaType.Null) { schema.Enum.Add(JValue.CreateNull()); } IList <EnumValue <long> > enumValues = EnumUtils.GetNamesAndValues <long>(contract.NonNullableUnderlyingType); foreach (EnumValue <long> enumValue in enumValues) { JToken value = JToken.FromObject(enumValue.Value); schema.Enum.Add(value); } } Type enumDataType = DataAnnotationHelpers.GetEnumDataType(memberProperty); if (enumDataType != null && CollectionUtils.IsNullOrEmpty(schema._enum)) { IList <EnumValue <long> > enumValues = EnumUtils.GetNamesAndValues <long>(enumDataType); foreach (EnumValue <long> enumValue in enumValues) { JToken value = (JSchemaTypeHelpers.HasFlag(schema.Type, JSchemaType.String)) ? enumValue.Name : JToken.FromObject(enumValue.Value); schema.Enum.Add(value); } } break; case JsonContractType.String: JSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType)) ? JSchemaType.String : AddNullType(JSchemaType.String, valueRequired); schema.Type = schemaType; schema.MinimumLength = DataAnnotationHelpers.GetMinLength(memberProperty); schema.MaximumLength = DataAnnotationHelpers.GetMaxLength(memberProperty); break; case JsonContractType.Dictionary: schema.Type = AddNullType(JSchemaType.Object, valueRequired); schema.MinimumProperties = DataAnnotationHelpers.GetMinLength(memberProperty); schema.MaximumProperties = DataAnnotationHelpers.GetMaxLength(memberProperty); Type keyType; Type valueType; ReflectionUtils.GetDictionaryKeyValueTypes(contract.NonNullableUnderlyingType, out keyType, out valueType); if (keyType != null) { JsonContract keyContract = _generator.ContractResolver.ResolveContract(keyType); // can be converted to a string if (keyContract.ContractType == JsonContractType.Primitive) { schema.AdditionalProperties = GenerateInternal(valueType, Required.Default, null, (JsonDictionaryContract)contract, null); } } break; case JsonContractType.Serializable: if (schema.Id == null) { schema.Id = GetTypeId(contract.NonNullableUnderlyingType, false); } schema.Type = AddNullType(JSchemaType.Object, valueRequired); schema.AllowAdditionalProperties = true; break; case JsonContractType.Dynamic: case JsonContractType.Linq: schema.Type = null; break; default: throw new JSchemaException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } } }
private JSchema GenerateInternal(Type type, Required?valueRequired, JsonProperty memberProperty, JsonContainerContract container, JSchemaGenerationProvider currentGenerationProvider) { ValidationUtils.ArgumentNotNull(type, nameof(type)); Type nonNullableType = ReflectionUtils.IsNullableType(type) ? Nullable.GetUnderlyingType(type) : type; Uri explicitId = GetTypeId(nonNullableType, true); JsonContract contract = _generator.ContractResolver.ResolveContract(type); Required resolvedRequired = valueRequired ?? _generator.DefaultRequired; TypeSchemaKey key = CreateKey(resolvedRequired, memberProperty, contract); if (ShouldReferenceType(contract)) { TypeSchema typeSchema = _typeSchemas.SingleOrDefault(s => s.Key.Equals(key)); if (typeSchema != null) { return(typeSchema.Schema); } } JSchema schema = null; JSchemaGenerationProvider provider = ResolveTypeProvider(nonNullableType, memberProperty); if (provider != null && provider != currentGenerationProvider) { JSchemaTypeGenerationContext context = new JSchemaTypeGenerationContext(type, resolvedRequired, memberProperty, container, this); context.GenerationProvider = provider; schema = provider.GetSchema(context); if (schema == null) { throw new JSchemaException("Could not get schema for type '{0}' from provider '{1}'.".FormatWith(CultureInfo.InvariantCulture, type.FullName, provider.GetType().FullName)); } } if (_generator._generationProviders != null) { JSchemaTypeGenerationContext context = new JSchemaTypeGenerationContext(type, resolvedRequired, memberProperty, container, this); foreach (JSchemaGenerationProvider generationProvider in _generator._generationProviders) { if (generationProvider != currentGenerationProvider && generationProvider.CanGenerateSchema(context)) { context.GenerationProvider = generationProvider; schema = generationProvider.GetSchema(context); break; } } } if (schema != null) { if (ShouldReferenceType(contract)) { _typeSchemas.Add(new TypeSchema(key, schema)); } } else { schema = new JSchema(); if (explicitId != null) { schema.Id = explicitId; } if (ShouldReferenceType(contract)) { _typeSchemas.Add(new TypeSchema(key, schema)); } PopulateSchema(schema, contract, memberProperty, resolvedRequired); } return(schema); }
protected override JsonContract CreateContract(Type objectType) { JsonContract contract = base.CreateContract(objectType); // this will only be called once and then cached if (typeof(IDictionary).IsAssignableFrom(objectType)) { contract.Converter = new DictionaryKeysAreNotPropertyNamesJsonConverter(); } if (objectType == typeof(Facet)) { contract.Converter = new FacetConverter(); } if (objectType == typeof(Uri)) { contract.Converter = new UriJsonConverter(); } if (objectType == typeof(IAggregation)) { contract.Converter = new AggregationConverter(); } if (objectType == typeof(DateTime) || objectType == typeof(DateTime?)) { contract.Converter = new IsoDateTimeConverter(); } if (typeof(IHit <object>).IsAssignableFrom(objectType)) { contract.Converter = new DefaultHitConverter(); } if (objectType == typeof(MultiGetResponse)) { contract.Converter = new MultiGetHitConverter(); } if (objectType == typeof(PropertyNameMarker)) { contract.Converter = new PropertyNameMarkerConverter(this.ConnectionSettings); } if (objectType == typeof(PropertyPathMarker)) { contract.Converter = new PropertyPathMarkerConverter(this.ConnectionSettings); } if (objectType == typeof(SuggestResponse)) { contract.Converter = new SuggestResponseConverter(); } if (objectType == typeof(MultiSearchResponse)) { contract.Converter = new MultiSearchConverter(); } if (objectType == typeof(IDictionary <string, AnalyzerBase>)) { contract.Converter = new AnalyzerCollectionConverter(); } if (objectType == typeof(IDictionary <string, TokenFilterBase>)) { contract.Converter = new TokenFilterCollectionConverter(); } if (objectType == typeof(IDictionary <string, TokenizerBase>)) { contract.Converter = new TokenizerCollectionConverter(); } if (objectType == typeof(IDictionary <string, CharFilterBase>)) { contract.Converter = new CharFilterCollectionConverter(); } if (this.ConnectionSettings.ContractConverters.HasAny()) { foreach (var c in this.ConnectionSettings.ContractConverters) { var converter = c(objectType); if (converter == null) { continue; } contract.Converter = converter; break; } } return(contract); }
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { ValidationUtils.ArgumentNotNull(type, "type"); string typeId = this.GetTypeId(type, false); string typeId2 = this.GetTypeId(type, true); if (!string.IsNullOrEmpty(typeId)) { JsonSchema schema = this._resolver.GetSchema(typeId); if (schema != null) { if (valueRequired != Required.Always && !JsonSchemaGenerator.HasFlag(schema.Type, JsonSchemaType.Null)) { schema.Type |= JsonSchemaType.Null; } if (required && schema.Required != true) { schema.Required = new bool?(true); } return(schema); } } if (this._stack.Any((JsonSchemaGenerator.TypeSchema tc) => tc.Type == type)) { throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); } JsonContract jsonContract = this.ContractResolver.ResolveContract(type); JsonConverter jsonConverter; if ((jsonConverter = jsonContract.Converter) != null || (jsonConverter = jsonContract.InternalConverter) != null) { JsonSchema schema2 = jsonConverter.GetSchema(); if (schema2 != null) { return(schema2); } } this.Push(new JsonSchemaGenerator.TypeSchema(type, new JsonSchema())); if (typeId2 != null) { this.CurrentSchema.Id = typeId2; } if (required) { this.CurrentSchema.Required = new bool?(true); } this.CurrentSchema.Title = this.GetTitle(type); this.CurrentSchema.Description = this.GetDescription(type); if (jsonConverter != null) { this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any); } else { switch (jsonContract.ContractType) { case JsonContractType.Object: this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); this.GenerateObjectSchema(type, (JsonObjectContract)jsonContract); goto IL_51E; case JsonContractType.Array: { this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Array, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); JsonArrayAttribute jsonArrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute; bool flag = jsonArrayAttribute == null || jsonArrayAttribute.AllowNullItems; Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { this.CurrentSchema.Items = new List <JsonSchema>(); this.CurrentSchema.Items.Add(this.GenerateInternal(collectionItemType, (!flag) ? Required.Always : Required.Default, false)); goto IL_51E; } goto IL_51E; } case JsonContractType.Primitive: { this.CurrentSchema.Type = new JsonSchemaType?(this.GetJsonSchemaType(type, valueRequired)); if (!(this.CurrentSchema.Type == JsonSchemaType.Integer) || !type.IsEnum() || type.IsDefined(typeof(FlagsAttribute), true)) { goto IL_51E; } this.CurrentSchema.Enum = new List <JToken>(); EnumValues <long> namesAndValues = EnumUtils.GetNamesAndValues <long>(type); using (IEnumerator <EnumValue <long> > enumerator = namesAndValues.GetEnumerator()) { while (enumerator.MoveNext()) { EnumValue <long> current = enumerator.Current; JToken item = JToken.FromObject(current.Value); this.CurrentSchema.Enum.Add(item); } goto IL_51E; } break; } case JsonContractType.String: break; case JsonContractType.Dictionary: { this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); Type type2; Type type3; ReflectionUtils.GetDictionaryKeyValueTypes(type, out type2, out type3); if (!(type2 != null)) { goto IL_51E; } JsonContract jsonContract2 = this.ContractResolver.ResolveContract(type2); if (jsonContract2.ContractType == JsonContractType.Primitive) { this.CurrentSchema.AdditionalProperties = this.GenerateInternal(type3, Required.Default, false); goto IL_51E; } goto IL_51E; } case JsonContractType.Dynamic: case JsonContractType.Linq: this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any); goto IL_51E; case JsonContractType.Serializable: this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); this.GenerateISerializableContract(type, (JsonISerializableContract)jsonContract); goto IL_51E; default: throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContract)); } JsonSchemaType value = (!ReflectionUtils.IsNullable(jsonContract.UnderlyingType)) ? JsonSchemaType.String : this.AddNullType(JsonSchemaType.String, valueRequired); this.CurrentSchema.Type = new JsonSchemaType?(value); } IL_51E: return(this.Pop().Schema); }
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool optional) { ValidationUtils.ArgumentNotNull(type, "type"); string resolvedId = GetTypeId(type, false); string explicitId = GetTypeId(type, true); if (!string.IsNullOrEmpty(resolvedId)) { JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId); if (resolvedSchema != null) { // resolved schema is not null but referencing member allows nulls // change resolved schema to allow nulls. hacky but what are ya gonna do? if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null)) { resolvedSchema.Type |= JsonSchemaType.Null; } if (optional && resolvedSchema.Optional != true) { resolvedSchema.Optional = true; } return(resolvedSchema); } } // test for unresolved circular reference if (_stack.Any(tc => tc.Type == type)) { throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); } JsonContract contract = ContractResolver.ResolveContract(type); JsonConverter converter; if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null) { JsonSchema converterSchema = converter.GetSchema(); if (converterSchema != null) { return(converterSchema); } } Push(new TypeSchema(type, new JsonSchema())); if (explicitId != null) { CurrentSchema.Id = explicitId; } if (optional) { CurrentSchema.Optional = true; } CurrentSchema.Title = GetTitle(type); CurrentSchema.Description = GetDescription(type); if (converter != null) { // todo: Add GetSchema to JsonConverter and use here? CurrentSchema.Type = JsonSchemaType.Any; } else if (contract is JsonDictionaryContract) { CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); Type keyType; Type valueType; ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType); if (keyType != null) { // can be converted to a string if (typeof(IConvertible).IsAssignableFrom(keyType)) { CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false); } } } else if (contract is JsonArrayContract) { CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired); CurrentSchema.Id = GetTypeId(type, false); JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute; bool allowNullItem = (arrayAttribute != null) ? arrayAttribute.AllowNullItems : true; Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { CurrentSchema.Items = new List <JsonSchema>(); CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false)); } } else if (contract is JsonPrimitiveContract) { CurrentSchema.Type = GetJsonSchemaType(type, valueRequired); if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum && !type.IsDefined(typeof(FlagsAttribute), true)) { CurrentSchema.Enum = new List <JToken>(); CurrentSchema.Options = new Dictionary <JToken, string>(); EnumValues <long> enumValues = EnumUtils.GetNamesAndValues <long>(type); foreach (EnumValue <long> enumValue in enumValues) { JToken value = JToken.FromObject(enumValue.Value); CurrentSchema.Enum.Add(value); CurrentSchema.Options.Add(value, enumValue.Name); } } } else if (contract is JsonObjectContract) { CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateObjectSchema(type, (JsonObjectContract)contract); } #if !SILVERLIGHT && !PocketPC else if (contract is JsonISerializableContract) { CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateISerializableContract(type, (JsonISerializableContract)contract); } #endif else if (contract is JsonStringContract) { JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType)) ? JsonSchemaType.String : AddNullType(JsonSchemaType.String, valueRequired); CurrentSchema.Type = schemaType; } else if (contract is JsonLinqContract) { CurrentSchema.Type = JsonSchemaType.Any; } else { throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } return(Pop().Schema); }
protected override void WriteJsonValue(JsonWriter writer, JsonContract contract, string property = null) { writer.WriteValue(title); }
private bool OverrideCreatorIfNeeded(Type type, ModelObjectSerializationContext context, JsonContract result) { if (result is JsonObjectContract objectContract) { var provider = GetFactoryProvider(type, objectContract); if (provider != null) { objectContract.OverrideCreator = provider.Invoke(context); return(true); } } return(false); }
public override object PopulateMember(string memberName, JsonContract contract, JsonReader reader, Type objectType, object targetObject, JsonSerializerReader internalReader) { GameObject gameObject = (GameObject)targetObject; bool finished; switch (memberName) { case "name": gameObject.name = reader.ReadAsString(); break; case "tag": gameObject.tag = reader.ReadAsString(); break; case "active": gameObject.SetActive(reader.ReadAsBoolean().GetValueOrDefault()); break; case "isStatic": gameObject.isStatic = reader.ReadAsBoolean().GetValueOrDefault(); break; case "layer": gameObject.layer = reader.ReadAsInt32().GetValueOrDefault(); break; case "hideFlags": gameObject.hideFlags = (HideFlags)reader.ReadAsInt32().GetValueOrDefault(); break; case "components": // Skip property name reader.ReadAndAssert(); // Skipy array start reader.ReadAndAssert(); finished = false; do { switch (reader.TokenType) { case JsonToken.EndArray: finished = true; break; default: if (reader.TokenType != JsonToken.StartObject) { reader.Read(); continue; } reader.ReadAndAssert(); string qualifiedTypeName = reader.ReadAsString(); Type componentType = null; JsonContract componentContract = null; internalReader.ResolveTypeName(reader, ref componentType, ref componentContract, null, null, null, qualifiedTypeName); reader.ReadAndAssert(); reader.ReadAndAssert(); Component component = gameObject.GetComponent(componentType); if (component == null) { component = gameObject.AddComponent(componentType); } internalReader.DeserializeInto(reader, componentType, component, false); break; } } while (!finished); break; case "children": // Skip property name reader.ReadAndAssert(); // Skipy array start reader.ReadAndAssert(); finished = false; do { switch (reader.TokenType) { case JsonToken.EndArray: finished = true; break; default: if (reader.TokenType != JsonToken.StartObject) { reader.Read(); continue; } GameObject child = internalReader.Deserialize <GameObject>(reader); child.transform.SetParent(gameObject.transform); //child.transform.parent = gameObject.transform; break; } } while (!finished); break; default: base.PopulateMember(memberName, contract, reader, objectType, targetObject, internalReader); break; } return(gameObject); }
private static TypeSchemaKey CreateKey(Required valueRequired, JsonProperty memberProperty, JsonContract contract) { int?minLength = DataAnnotationHelpers.GetMinLength(memberProperty); int?maxLength = DataAnnotationHelpers.GetMaxLength(memberProperty); TypeSchemaKey key = new TypeSchemaKey(contract.UnderlyingType, valueRequired, minLength, maxLength); return(key); }
private JSchema GenerateInternal(Type type, Required valueRequired, JsonProperty memberProperty, JsonContainerContract container) { ValidationUtils.ArgumentNotNull(type, "type"); Type nonNullableType = ReflectionUtils.IsNullableType(type) ? Nullable.GetUnderlyingType(type) : type; Uri explicitId = GetTypeId(nonNullableType, true); JsonContract contract = ContractResolver.ResolveContract(type); var key = CreateKey(valueRequired, memberProperty, contract); switch (contract.ContractType) { case JsonContractType.Object: case JsonContractType.Array: case JsonContractType.Dictionary: TypeSchema typeSchema = _typeSchemas.SingleOrDefault(s => s.Key.Equals(key)); if (typeSchema != null) { return(typeSchema.Schema); } break; } JSchema schema = null; JSchemaGenerationProvider provider = ResolveTypeProvider(nonNullableType, memberProperty); if (provider != null) { JSchemaTypeGenerationContext context = new JSchemaTypeGenerationContext(type, valueRequired, memberProperty, container, this); schema = provider.GetSchema(context); if (schema == null) { throw new JSchemaException("Could not get schema for type '{0}' from provider '{1}'.".FormatWith(CultureInfo.InvariantCulture, type.FullName, provider.GetType().FullName)); } } if (_generationProviders != null) { JSchemaTypeGenerationContext context = new JSchemaTypeGenerationContext(type, valueRequired, memberProperty, container, this); foreach (JSchemaGenerationProvider generationProvider in _generationProviders) { schema = generationProvider.GetSchema(context); } } if (schema != null) { _typeSchemas.Add(new TypeSchema(key, schema)); return(schema); } schema = new JSchema(); if (explicitId != null) { schema.Id = explicitId; } switch (contract.ContractType) { case JsonContractType.Object: case JsonContractType.Array: case JsonContractType.Dictionary: _typeSchemas.Add(new TypeSchema(key, schema)); break; } return(PopulateSchema(schema, contract, memberProperty, valueRequired)); }
void CheckValue(object value, StorableNode node = null) { IStorable storable; if (value == null) { return; } if (stack.Any(o => Object.ReferenceEquals(o, value))) { // Value in stack, return to avoid dependency cycles. return; } stack.Push(value); storable = value as IStorable; if (storable != null) { if (node == null) { node = new StorableNode(storable); } // Update parent and children relations if (current != null) { if (current.Deleted) { node.Deleted = true; } else { current.Children.Add(node); } } if (!node.Deleted) { aliveStorables.Add(storable); } node.Parent = current; current = node; } // Figure out the type of object we are dealing with and parse it accordingly. // Primitives are ignored (not being objects containers) and lists and dictionaries // are traversed through all their children. JsonContract valueContract = resolver.ResolveContract(value.GetType()); if (valueContract is JsonObjectContract) { CheckObject(value, valueContract as JsonObjectContract); } else if (valueContract is JsonArrayContract) { CheckEnumerable(value as IEnumerable, valueContract as JsonArrayContract); } else if (valueContract is JsonDictionaryContract) { CheckEnumerable((value as IDictionary).Values, valueContract as JsonArrayContract); } else { // Skip primitive value } // Now try to find orphaned objects and create nodes with the Deleted flags. // These objects are currently saved in the database and cached in IStorable.SavedChildren but // the current IStorable does not reference them anymore as real children. // We used this cache to find the orphaned children and mark them with the Deleted flag. if (storable != null) { if (storable.DeleteChildren && storable.SavedChildren != null) { var orphaned = storable.SavedChildren.Except(node.Children.Select(n => n.Storable)); foreach (IStorable st in orphaned) { deletedStorables.Add(st); StorableNode onode = new StorableNode(st); onode.Deleted = true; CheckValue(st, onode); } } current = current.Parent; } stack.Pop(); }
protected override bool CanCustomize(JSchemaTypeGenerationContext context, JsonContract contract, Type type) { return(contract is JsonObjectContract); }
protected override JsonContract CreateContract(Type objectType) { JsonContract contract = base.CreateContract(objectType); // this will only be called once and then cached if (objectType == typeof(Uri)) { contract.Converter = UriConverter.Instance; } else if (objectType == typeof(DateTime)) { contract.Converter = DateTimeConverter.Instance; } else if (objectType == typeof(Version)) { contract.Converter = VersionConverter.Instance; } else if (objectType == typeof(SarifVersion)) { contract.Converter = SarifVersionConverter.Instance; } else if (objectType == typeof(AnnotatedCodeLocationKind)) { contract.Converter = EnumConverter.Instance; } else if (objectType == typeof(AnnotatedCodeLocationImportance)) { contract.Converter = EnumConverter.Instance; } else if (objectType == typeof(ResultLevel)) { contract.Converter = EnumConverter.Instance; } else if (objectType == typeof(NotificationLevel)) { contract.Converter = EnumConverter.Instance; } else if (objectType == typeof(AlgorithmKind)) { contract.Converter = EnumConverter.Instance; } else if (objectType == typeof(BaselineState)) { contract.Converter = EnumConverter.Instance; } else if (objectType == typeof(SuppressionStates)) { contract.Converter = FlagsEnumConverter.Instance; } else if (objectType == typeof(Dictionary <string, IRule>)) { contract.Converter = RuleDictionaryConverter.Instance; } else if (objectType == typeof(IDictionary <string, SerializedPropertyInfo>)) { contract.Converter = PropertyBagConverter.Instance; } return(contract); }
public ContractCreatedEventArgs(JsonContract contract, Type objectType) { this.Contract = contract; this.ObjectType = objectType; }
public NowCondition(JsonContract.Condition_NowContract cond) { Condition = ParseCondition(cond.code); }
private static TypeSchemaKey CreateKey(Required valueRequired, JsonProperty memberProperty, JsonContract contract) { int?minLength = DataAnnotationHelpers.GetMinLength(memberProperty); int?maxLength = DataAnnotationHelpers.GetMaxLength(memberProperty); Required resolvedRequired; switch (valueRequired) { case Required.Default: case Required.AllowNull: resolvedRequired = Required.AllowNull; break; case Required.Always: case Required.DisallowNull: resolvedRequired = Required.DisallowNull; break; default: throw new ArgumentOutOfRangeException(nameof(valueRequired)); } TypeSchemaKey key = new TypeSchemaKey(contract.UnderlyingType, resolvedRequired, minLength, maxLength); return(key); }
protected override bool CanGenerateSchemaFor(ModelMetadata modelMetadata, JsonContract jsonContract) { return(jsonContract is JsonObjectContract); }
private static void TrySimplfyingJson(RavenJObject jObject, JsonContract contract) { var objectContract = contract as JsonObjectContract; if (objectContract == null) { return; } var deferredActions = new List <Action>(); foreach (var kvp in jObject) { var prop = kvp; if (prop.Value == null) { continue; } var obj = prop.Value as RavenJObject; if (obj == null) { continue; } var jsonProperty = objectContract.Properties.GetClosestMatchProperty(prop.Key); if (ShouldSimplfyJsonBasedOnType(obj.Value <string>("$type"), jsonProperty) == false) { continue; } if (obj.ContainsKey("$values") == false) { deferredActions.Add(() => obj.Remove("$type")); } else { deferredActions.Add(() => jObject[prop.Key] = obj["$values"]); } } foreach (var deferredAction in deferredActions) { deferredAction(); } foreach (var prop in jObject.Where(prop => prop.Value != null)) { switch (prop.Value.Type) { case JTokenType.Array: foreach (var item in ((RavenJArray)prop.Value)) { var ravenJObject = item as RavenJObject; if (ravenJObject != null) { TrySimplfyingJson(ravenJObject, contract); } } break; case JTokenType.Object: TrySimplfyingJson((RavenJObject)prop.Value, contract); break; } } }
public DailyCondition(JsonContract.ConditionContract cond) { DayCond = ParseCondition(cond.code_d); NightCond = ParseCondition(cond.code_n); }
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { ValidationUtils.ArgumentNotNull(type, "type"); string resolvedId = GetTypeId(type, false); string explicitId = GetTypeId(type, true); if (!string.IsNullOrEmpty(resolvedId)) { JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId); if (resolvedSchema != null) { // resolved schema is not null but referencing member allows nulls // change resolved schema to allow nulls. hacky but what are ya gonna do? if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null)) { resolvedSchema.Type |= JsonSchemaType.Null; } if (required && resolvedSchema.Required != true) { resolvedSchema.Required = true; } return(resolvedSchema); } } // test for unresolved circular reference if (_stack.Any(tc => tc.Type == type)) { throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); } JsonContract contract = ContractResolver.ResolveContract(type); JsonConverter converter; if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null) { JsonSchema converterSchema = converter.GetSchema(); if (converterSchema != null) { return(converterSchema); } } Push(new TypeSchema(type, new JsonSchema())); if (explicitId != null) { CurrentSchema.Id = explicitId; } if (required) { CurrentSchema.Required = true; } CurrentSchema.Title = GetTitle(type); CurrentSchema.Description = GetDescription(type); if (converter != null) { // todo: Add GetSchema to JsonConverter and use here? CurrentSchema.Type = JsonSchemaType.Any; } else { switch (contract.ContractType) { case JsonContractType.Object: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateObjectSchema(type, (JsonObjectContract)contract); break; case JsonContractType.Array: CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired); CurrentSchema.Id = GetTypeId(type, false); JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetCachedAttribute <JsonArrayAttribute>(type); bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems); Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { CurrentSchema.Items = new List <JsonSchema>(); CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false)); } break; case JsonContractType.Primitive: CurrentSchema.Type = GetJsonSchemaType(type, valueRequired); if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof(FlagsAttribute), true)) { CurrentSchema.Enum = new List <JToken>(); IList <EnumValue <long> > enumValues = EnumUtils.GetNamesAndValues <long>(type); foreach (EnumValue <long> enumValue in enumValues) { JToken value = JToken.FromObject(enumValue.Value); CurrentSchema.Enum.Add(value); } } break; case JsonContractType.String: JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType)) ? JsonSchemaType.String : AddNullType(JsonSchemaType.String, valueRequired); CurrentSchema.Type = schemaType; break; case JsonContractType.Dictionary: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); Type keyType; Type valueType; ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType); if (keyType != null) { JsonContract keyContract = ContractResolver.ResolveContract(keyType); // can be converted to a string if (keyContract.ContractType == JsonContractType.Primitive) { CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false); } } break; #if !(NETFX_CORE || PORTABLE || PORTABLE40) case JsonContractType.Serializable: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateISerializableContract(type, (JsonISerializableContract)contract); break; #endif #if !(NET35 || NET20 || PORTABLE40) case JsonContractType.Dynamic: #endif case JsonContractType.Linq: CurrentSchema.Type = JsonSchemaType.Any; break; default: throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } } return(Pop().Schema); }
// Token: 0x060013CD RID: 5069 RVA: 0x00068C14 File Offset: 0x00066E14 private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { ValidationUtils.ArgumentNotNull(type, "type"); string typeId = this.GetTypeId(type, false); string typeId2 = this.GetTypeId(type, true); if (!StringUtils.IsNullOrEmpty(typeId)) { JsonSchema schema = this._resolver.GetSchema(typeId); if (schema != null) { if (valueRequired != Required.Always && !JsonSchemaGenerator.HasFlag(schema.Type, JsonSchemaType.Null)) { schema.Type |= JsonSchemaType.Null; } if (required) { bool?required2 = schema.Required; if (!(required2.GetValueOrDefault() & required2 != null)) { schema.Required = new bool?(true); } } return(schema); } } if (this._stack.Any((JsonSchemaGenerator.TypeSchema tc) => tc.Type == type)) { throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); } JsonContract jsonContract = this.ContractResolver.ResolveContract(type); bool flag = (jsonContract.Converter ?? jsonContract.InternalConverter) != null; this.Push(new JsonSchemaGenerator.TypeSchema(type, new JsonSchema())); if (typeId2 != null) { this.CurrentSchema.Id = typeId2; } if (required) { this.CurrentSchema.Required = new bool?(true); } this.CurrentSchema.Title = this.GetTitle(type); this.CurrentSchema.Description = this.GetDescription(type); if (flag) { this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any); } else { switch (jsonContract.ContractType) { case JsonContractType.Object: this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); this.GenerateObjectSchema(type, (JsonObjectContract)jsonContract); break; case JsonContractType.Array: { this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Array, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); JsonArrayAttribute cachedAttribute = JsonTypeReflector.GetCachedAttribute <JsonArrayAttribute>(type); bool flag2 = cachedAttribute == null || cachedAttribute.AllowNullItems; Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { this.CurrentSchema.Items = new List <JsonSchema>(); this.CurrentSchema.Items.Add(this.GenerateInternal(collectionItemType, (!flag2) ? Required.Always : Required.Default, false)); } break; } case JsonContractType.Primitive: { this.CurrentSchema.Type = new JsonSchemaType?(this.GetJsonSchemaType(type, valueRequired)); JsonSchemaType?type2 = this.CurrentSchema.Type; if ((type2.GetValueOrDefault() == JsonSchemaType.Integer & type2 != null) && type.IsEnum() && !type.IsDefined(typeof(FlagsAttribute), true)) { this.CurrentSchema.Enum = new List <JToken>(); EnumInfo enumValuesAndNames = EnumUtils.GetEnumValuesAndNames(type); for (int i = 0; i < enumValuesAndNames.Names.Length; i++) { ulong value = enumValuesAndNames.Values[i]; JToken item = JToken.FromObject(Enum.ToObject(type, value)); this.CurrentSchema.Enum.Add(item); } } break; } case JsonContractType.String: { JsonSchemaType value2 = (!ReflectionUtils.IsNullable(jsonContract.UnderlyingType)) ? JsonSchemaType.String : this.AddNullType(JsonSchemaType.String, valueRequired); this.CurrentSchema.Type = new JsonSchemaType?(value2); break; } case JsonContractType.Dictionary: { this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); Type type3; Type type4; ReflectionUtils.GetDictionaryKeyValueTypes(type, out type3, out type4); if (type3 != null && this.ContractResolver.ResolveContract(type3).ContractType == JsonContractType.Primitive) { this.CurrentSchema.AdditionalProperties = this.GenerateInternal(type4, Required.Default, false); } break; } case JsonContractType.Dynamic: case JsonContractType.Linq: this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any); break; case JsonContractType.Serializable: this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); this.GenerateISerializableContract(type, (JsonISerializableContract)jsonContract); break; default: throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContract)); } } return(this.Pop().Schema); }
static Program() { s_userContract = new JsonContract<User>(); s_userContract.SimpleProperty(u => u.UserName).Name("Name"); s_userContract.SimpleProperty(u => u.Age); s_postContract = new JsonContract<Post>(); s_postContract.SimpleProperty(p => p.Title); s_postContract.SimpleProperty(p => p.CreateTime).Converter(new DataTimeConverter()); s_categoryContract = new JsonContract<Category>(); s_categoryContract.SimpleProperty(p => p.Name); s_categoryContract.ComplexProperty(p => p.Author).Contract(s_userContract); s_categoryContract.ArrayProperty(p => p.Posts).ElementContract(s_postContract); }
internal bool ReadForType(JsonContract contract, bool hasConverter) { // don't read properties with converters as a specific value // the value might be a string which will then get converted which will error if read as date for example if (hasConverter) { return(Read()); } ReadType t = (contract != null) ? contract.InternalReadType : ReadType.Read; switch (t) { case ReadType.Read: return(ReadAndMoveToContent()); case ReadType.ReadAsInt32: ReadAsInt32(); break; case ReadType.ReadAsInt64: bool result = ReadAndMoveToContent(); if (TokenType == JsonToken.Undefined) { throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } return(result); case ReadType.ReadAsDecimal: ReadAsDecimal(); break; case ReadType.ReadAsDouble: ReadAsDouble(); break; case ReadType.ReadAsBytes: ReadAsBytes(); break; case ReadType.ReadAsBoolean: ReadAsBoolean(); break; case ReadType.ReadAsString: ReadAsString(); break; case ReadType.ReadAsDateTime: ReadAsDateTime(); break; #if HAVE_DATE_TIME_OFFSET case ReadType.ReadAsDateTimeOffset: ReadAsDateTimeOffset(); break; #endif default: throw new ArgumentOutOfRangeException(); } return(TokenType != JsonToken.None); }
public Suggestion(JsonContract.SuggestionContract suggestion) { Brief = suggestion.brf; Text = suggestion.txt; }
protected abstract void WriteJsonValue(JsonWriter writer, JsonContract contract, string property = null);
protected override OpenApiSchema GenerateSchemaFor(ModelMetadata modelMetadata, SchemaRepository schemaRepository, JsonContract jsonContract) { var jsonObjectContract = (JsonObjectContract)jsonContract; var additionalProperties = (jsonObjectContract.ExtensionDataValueType != null) ? SchemaGenerator.GenerateSchema(modelMetadata.GetMetadataForType(jsonObjectContract.ExtensionDataValueType), schemaRepository) : null; var schema = new OpenApiSchema { Type = "object", Properties = new Dictionary <string, OpenApiSchema>(), Required = new SortedSet <string>(), AdditionalPropertiesAllowed = (additionalProperties != null), AdditionalProperties = additionalProperties }; foreach (var jsonProperty in jsonObjectContract.Properties) { var propertyMetadata = modelMetadata.Properties[jsonProperty.UnderlyingName] ?? modelMetadata.GetMetadataForType(jsonProperty.PropertyType); var propertyAttributes = propertyMetadata.GetCustomAttributes(); if (propertyAttributes.OfType <ObsoleteAttribute>().Any() || jsonProperty.Ignored) { continue; } schema.Properties.Add(jsonProperty.PropertyName, GeneratePropertySchemaFor(propertyMetadata, schemaRepository, jsonProperty)); if (propertyAttributes.OfType <RequiredAttribute>().Any() || jsonProperty.Required == Required.AllowNull || jsonProperty.Required == Required.Always) { schema.Required.Add(jsonProperty.PropertyName); } } return(schema); }
/// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object?ReadJson( JsonReader reader, Type objectType, object?existingValue, JsonSerializer serializer ) { if (reader.TokenType == JsonToken.Null) { if (!ReflectionUtils.IsNullableType(objectType)) { throw JsonSerializationException.Create( reader, "Cannot convert null value to KeyValuePair." ); } return(null); } object?key = null; object?value = null; reader.ReadAndAssert(); Type t = ReflectionUtils.IsNullableType(objectType) ? Nullable.GetUnderlyingType(objectType) : objectType; ReflectionObject reflectionObject = ReflectionObjectPerType.Get(t); JsonContract keyContract = serializer.ContractResolver.ResolveContract( reflectionObject.GetType(KeyName) ); JsonContract valueContract = serializer.ContractResolver.ResolveContract( reflectionObject.GetType(ValueName) ); while (reader.TokenType == JsonToken.PropertyName) { string propertyName = reader.Value !.ToString(); if (string.Equals(propertyName, KeyName, StringComparison.OrdinalIgnoreCase)) { reader.ReadForTypeAndAssert(keyContract, false); key = serializer.Deserialize(reader, keyContract.UnderlyingType); } else if (string.Equals(propertyName, ValueName, StringComparison.OrdinalIgnoreCase)) { reader.ReadForTypeAndAssert(valueContract, false); value = serializer.Deserialize(reader, valueContract.UnderlyingType); } else { reader.Skip(); } reader.ReadAndAssert(); } return(reflectionObject.Creator !(key, value)); }
/// <summary> /// Determines which contract type is created for the given type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns>A Newtonsoft.Json.Serialization.JsonContract for the given type.</returns> protected override JsonContract CreateContract(Type objectType) { JsonContract contract = base.CreateContract(objectType); //if ((objectType == typeof(ColliderType)) || // (objectType == typeof(CollisionDetectionMode)) || // (objectType == typeof(GradientMode)) || // (objectType == typeof(MotionVectorGenerationMode)) || // (objectType == typeof(PhysicMaterialCombine)) || // (objectType == typeof(RigidbodyInterpolation)) || // (objectType == typeof(SpriteMaskInteraction)) || // (objectType == typeof(WrapMode)) || // (objectType == typeof(WeightedMode)) //) //{ // contract.Converter = new StringEnumConverter(new DefaultNamingStrategy(), allowIntegerValues: false); //} //// Rendering //if ((objectType == typeof(CullMode)) || // (objectType == typeof(LightmapBakeType)) || // (objectType == typeof(LightProbeUsage)) || // (objectType == typeof(LightRenderMode)) || // (objectType == typeof(LightShadowResolution)) || // (objectType == typeof(LightShadows)) || // (objectType == typeof(LightShape)) || // (objectType == typeof(LightType)) || // (objectType == typeof(ReflectionProbeUsage)) || // (objectType == typeof(ShadowCastingMode)) //) //{ // contract.Converter = new StringEnumConverter(new DefaultNamingStrategy(), allowIntegerValues: false); //} //// ParticleSystem //if ((objectType == typeof(ParticleSystemAnimationMode)) || // (objectType == typeof(ParticleSystemAnimationRowMode)) || // (objectType == typeof(ParticleSystemAnimationTimeMode)) || // (objectType == typeof(ParticleSystemAnimationType)) || // (objectType == typeof(ParticleSystemCollisionMode)) || // (objectType == typeof(ParticleSystemCollisionQuality)) || // (objectType == typeof(ParticleSystemCollisionType)) || // (objectType == typeof(ParticleSystemCullingMode)) || // (objectType == typeof(ParticleSystemCurveMode)) || // (objectType == typeof(ParticleSystemEmitterVelocityMode)) || // (objectType == typeof(ParticleSystemGameObjectFilter)) || // (objectType == typeof(ParticleSystemGradientMode)) || // (objectType == typeof(ParticleSystemInheritVelocityMode)) || // (objectType == typeof(ParticleSystemMeshShapeType)) || // (objectType == typeof(ParticleSystemNoiseQuality)) || // (objectType == typeof(ParticleSystemOverlapAction)) || // (objectType == typeof(ParticleSystemRenderMode)) || // (objectType == typeof(ParticleSystemRenderSpace)) || // (objectType == typeof(ParticleSystemRingBufferMode)) || // (objectType == typeof(ParticleSystemScalingMode)) || // (objectType == typeof(ParticleSystemShapeMultiModeValue)) || // (objectType == typeof(ParticleSystemShapeTextureChannel)) || // (objectType == typeof(ParticleSystemShapeType)) || // (objectType == typeof(ParticleSystemSimulationSpace)) || // (objectType == typeof(ParticleSystemSortMode) || // (objectType == typeof(ParticleSystemStopAction)) || // (objectType == typeof(ParticleSystemTrailMode)) || // (objectType == typeof(ParticleSystemTrailTextureMode)) //) //) //{ // contract.Converter = new StringEnumConverter(new DefaultNamingStrategy(), allowIntegerValues: false); //} //// Shader Properties (Particle) //if ((objectType == typeof(ParticleBlendMode)) || // (objectType == typeof(ParticleColorMode)) || // (objectType == typeof(ParticleFlipBookMode)) //) //{ // contract.Converter = new StringEnumConverter(new DefaultNamingStrategy(), allowIntegerValues: false); //} //// Shader Properties (Skybox) //if ((objectType == typeof(SkyboxImageType)) || // (objectType == typeof(SkyboxLayout)) || // (objectType == typeof(SkyboxMapping)) || // (objectType == typeof(SkyboxSunDisk)) //) //{ // contract.Converter = new StringEnumConverter(new DefaultNamingStrategy(), allowIntegerValues: false); //} // Shader Properties (MToon) if ((objectType == typeof(MToonCullMode)) || (objectType == typeof(MToonOutlineColorMode)) || (objectType == typeof(MToonOutlineWidthMode)) || (objectType == typeof(MToonRenderMode)) ) { contract.Converter = new StringEnumConverter(new CamelCaseNamingStrategy(), allowIntegerValues: false); } return(contract); }
private void PopulateSchema(JSchema schema, JsonContract contract, JsonProperty memberProperty, Required valueRequired) { schema.Title = GetTitle(contract.NonNullableUnderlyingType, memberProperty); schema.Description = GetDescription(contract.NonNullableUnderlyingType, memberProperty); JsonConverter converter; if (contract.Converter != null && contract.Converter.CanWrite) { converter = contract.Converter; } else if (contract.InternalConverter != null && contract.InternalConverter.CanWrite) { converter = contract.InternalConverter; } else { converter = null; } if (converter != null) { schema.Type = null; } else { switch (contract.ContractType) { case JsonContractType.Object: if (contract.NonNullableUnderlyingType == typeof(object)) { PopulatePrimativeSchema(schema, contract, memberProperty, valueRequired); } else { if (schema.Id == null) { schema.Id = GetTypeId(contract.NonNullableUnderlyingType, false); } schema.Type = AddNullType(JSchemaType.Object, valueRequired); GenerateObjectSchema(schema, contract.NonNullableUnderlyingType, (JsonObjectContract)contract); } break; case JsonContractType.Array: if (schema.Id == null) { schema.Id = GetTypeId(contract.NonNullableUnderlyingType, false); } schema.Type = AddNullType(JSchemaType.Array, valueRequired); schema.MinimumItems = DataAnnotationHelpers.GetMinLength(memberProperty); schema.MaximumItems = DataAnnotationHelpers.GetMaxLength(memberProperty); JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetCachedAttribute <JsonArrayAttribute>(contract.NonNullableUnderlyingType); Required?required = null; if (arrayAttribute != null && !arrayAttribute.AllowNullItems) { required = Required.Always; } Type collectionItemType = ReflectionUtils.GetCollectionItemType(contract.NonNullableUnderlyingType); if (collectionItemType != null) { schema.Items.Add(GenerateInternal(collectionItemType, required, null, (JsonArrayContract)contract, null)); } break; case JsonContractType.Primitive: PopulatePrimativeSchema(schema, contract, memberProperty, valueRequired); break; case JsonContractType.String: JSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType)) ? JSchemaType.String : AddNullType(JSchemaType.String, valueRequired); schema.Type = schemaType; schema.MinimumLength = DataAnnotationHelpers.GetMinLength(memberProperty); schema.MaximumLength = DataAnnotationHelpers.GetMaxLength(memberProperty); break; case JsonContractType.Dictionary: schema.Type = AddNullType(JSchemaType.Object, valueRequired); schema.MinimumProperties = DataAnnotationHelpers.GetMinLength(memberProperty); schema.MaximumProperties = DataAnnotationHelpers.GetMaxLength(memberProperty); ReflectionUtils.GetDictionaryKeyValueTypes(contract.NonNullableUnderlyingType, out Type keyType, out Type valueType); if (keyType != null) { JsonContract keyContract = _generator.ContractResolver.ResolveContract(keyType); // can be converted to a string if (keyContract.ContractType == JsonContractType.Primitive) { schema.AdditionalProperties = GenerateInternal(valueType, _generator.DefaultRequired, null, (JsonDictionaryContract)contract, null); } } break; case JsonContractType.Serializable: if (schema.Id == null) { schema.Id = GetTypeId(contract.NonNullableUnderlyingType, false); } schema.Type = AddNullType(JSchemaType.Object, valueRequired); schema.AllowAdditionalProperties = true; break; case JsonContractType.Dynamic: case JsonContractType.Linq: schema.Type = null; break; default: throw new JSchemaException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } } }