| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Diagnostics.CodeAnalysis; |
| | | 7 | | using System.Globalization; |
| | | 8 | | using System.Reflection; |
| | | 9 | | using System.Runtime.InteropServices; |
| | | 10 | | using System.Text.Json.Nodes; |
| | | 11 | | using System.Text.Json.Serialization; |
| | | 12 | | using System.Text.Json.Serialization.Metadata; |
| | | 13 | | |
| | | 14 | | namespace System.Text.Json.Schema |
| | | 15 | | { |
| | | 16 | | /// <summary> |
| | | 17 | | /// Functionality for exporting JSON schema from serialization contracts defined in <see cref="JsonTypeInfo"/>. |
| | | 18 | | /// </summary> |
| | | 19 | | public static class JsonSchemaExporter |
| | | 20 | | { |
| | | 21 | | /// <summary> |
| | | 22 | | /// Gets the JSON schema for <paramref name="type"/> as a <see cref="JsonNode"/> document. |
| | | 23 | | /// </summary> |
| | | 24 | | /// <param name="options">The options declaring the contract for the type.</param> |
| | | 25 | | /// <param name="type">The type for which to resolve a schema.</param> |
| | | 26 | | /// <param name="exporterOptions">The options object governing the export operation.</param> |
| | | 27 | | /// <returns>A JSON object containing the schema for <paramref name="type"/>.</returns> |
| | | 28 | | public static JsonNode GetJsonSchemaAsNode(this JsonSerializerOptions options, Type type, JsonSchemaExporterOpti |
| | 0 | 29 | | { |
| | 0 | 30 | | ArgumentNullException.ThrowIfNull(options); |
| | 0 | 31 | | ArgumentNullException.ThrowIfNull(type); |
| | | 32 | | |
| | 0 | 33 | | ValidateOptions(options); |
| | 0 | 34 | | JsonTypeInfo typeInfo = options.GetTypeInfoInternal(type); |
| | 0 | 35 | | return typeInfo.GetJsonSchemaAsNode(exporterOptions); |
| | 0 | 36 | | } |
| | | 37 | | |
| | | 38 | | /// <summary> |
| | | 39 | | /// Gets the JSON schema for <paramref name="typeInfo"/> as a <see cref="JsonNode"/> document. |
| | | 40 | | /// </summary> |
| | | 41 | | /// <param name="typeInfo">The contract from which to resolve the JSON schema.</param> |
| | | 42 | | /// <param name="exporterOptions">The options object governing the export operation.</param> |
| | | 43 | | /// <returns>A JSON object containing the schema for <paramref name="typeInfo"/>.</returns> |
| | | 44 | | public static JsonNode GetJsonSchemaAsNode(this JsonTypeInfo typeInfo, JsonSchemaExporterOptions? exporterOption |
| | 0 | 45 | | { |
| | 0 | 46 | | ArgumentNullException.ThrowIfNull(typeInfo); |
| | | 47 | | |
| | 0 | 48 | | ValidateOptions(typeInfo.Options); |
| | 0 | 49 | | exporterOptions ??= JsonSchemaExporterOptions.Default; |
| | | 50 | | |
| | 0 | 51 | | typeInfo.EnsureConfigured(); |
| | 0 | 52 | | GenerationState state = new(typeInfo.Options, exporterOptions); |
| | 0 | 53 | | JsonSchema schema = MapJsonSchemaCore(ref state, typeInfo); |
| | 0 | 54 | | return schema.ToJsonNode(exporterOptions); |
| | 0 | 55 | | } |
| | | 56 | | |
| | | 57 | | private static JsonSchema MapJsonSchemaCore( |
| | | 58 | | ref GenerationState state, |
| | | 59 | | JsonTypeInfo typeInfo, |
| | | 60 | | JsonPropertyInfo? propertyInfo = null, |
| | | 61 | | JsonConverter? customConverter = null, |
| | | 62 | | JsonNumberHandling? customNumberHandling = null, |
| | | 63 | | JsonTypeInfo? parentPolymorphicTypeInfo = null, |
| | | 64 | | bool parentPolymorphicTypeContainsTypesWithoutDiscriminator = false, |
| | | 65 | | bool parentPolymorphicTypeIsNonNullable = false, |
| | | 66 | | KeyValuePair<string, JsonSchema>? typeDiscriminator = null, |
| | | 67 | | bool cacheResult = true) |
| | 0 | 68 | | { |
| | 0 | 69 | | Debug.Assert(typeInfo.IsConfigured); |
| | | 70 | | |
| | 0 | 71 | | JsonSchemaExporterContext exporterContext = state.CreateContext(typeInfo, propertyInfo, parentPolymorphicTyp |
| | | 72 | | |
| | 0 | 73 | | if (cacheResult && typeInfo.Kind is not JsonTypeInfoKind.None && |
| | 0 | 74 | | state.TryGetExistingJsonPointer(exporterContext, out string? existingJsonPointer)) |
| | 0 | 75 | | { |
| | | 76 | | // The schema context has already been generated in the schema document, return a reference to it. |
| | 0 | 77 | | return CompleteSchema(ref state, new JsonSchema { Ref = existingJsonPointer }); |
| | | 78 | | } |
| | | 79 | | |
| | 0 | 80 | | JsonConverter effectiveConverter = customConverter ?? typeInfo.Converter; |
| | 0 | 81 | | JsonNumberHandling effectiveNumberHandling = customNumberHandling ?? typeInfo.NumberHandling ?? typeInfo.Opt |
| | 0 | 82 | | if (effectiveConverter.GetSchema(effectiveNumberHandling) is { } schema) |
| | 0 | 83 | | { |
| | | 84 | | // A schema has been provided by the converter. |
| | 0 | 85 | | return CompleteSchema(ref state, schema); |
| | | 86 | | } |
| | | 87 | | |
| | 0 | 88 | | if (parentPolymorphicTypeInfo is null && typeInfo.PolymorphismOptions is { DerivedTypes.Count: > 0 } polyOpt |
| | 0 | 89 | | { |
| | | 90 | | // This is the base type of a polymorphic type hierarchy. The schema for this type |
| | | 91 | | // will include an "anyOf" property with the schemas for all derived types. |
| | 0 | 92 | | string typeDiscriminatorKey = polyOptions.TypeDiscriminatorPropertyName; |
| | 0 | 93 | | List<JsonDerivedType> derivedTypes = new(polyOptions.DerivedTypes); |
| | | 94 | | |
| | 0 | 95 | | if (!typeInfo.Type.IsAbstract && !IsPolymorphicTypeThatSpecifiesItselfAsDerivedType(typeInfo)) |
| | 0 | 96 | | { |
| | | 97 | | // For non-abstract base types that haven't been explicitly configured, |
| | | 98 | | // add a trivial schema to the derived types since we should support it. |
| | 0 | 99 | | derivedTypes.Add(new JsonDerivedType(typeInfo.Type)); |
| | 0 | 100 | | } |
| | | 101 | | |
| | 0 | 102 | | bool containsTypesWithoutDiscriminator = derivedTypes.Exists(static derivedTypes => derivedTypes.TypeDis |
| | 0 | 103 | | JsonSchemaType schemaType = JsonSchemaType.Any; |
| | 0 | 104 | | List<JsonSchema>? anyOf = new(derivedTypes.Count); |
| | | 105 | | |
| | 0 | 106 | | state.PushSchemaNode(JsonSchema.AnyOfPropertyName); |
| | | 107 | | |
| | 0 | 108 | | foreach (JsonDerivedType derivedType in derivedTypes) |
| | 0 | 109 | | { |
| | 0 | 110 | | Debug.Assert(derivedType.TypeDiscriminator is null or int or string); |
| | | 111 | | |
| | 0 | 112 | | KeyValuePair<string, JsonSchema>? derivedTypeDiscriminator = null; |
| | 0 | 113 | | if (derivedType.TypeDiscriminator is { } discriminatorValue) |
| | 0 | 114 | | { |
| | 0 | 115 | | JsonNode discriminatorNode = discriminatorValue switch |
| | 0 | 116 | | { |
| | 0 | 117 | | string stringId => (JsonNode)stringId, |
| | 0 | 118 | | _ => (JsonNode)(int)discriminatorValue, |
| | 0 | 119 | | }; |
| | | 120 | | |
| | 0 | 121 | | JsonSchema discriminatorSchema = new() { Constant = discriminatorNode }; |
| | 0 | 122 | | derivedTypeDiscriminator = new(typeDiscriminatorKey, discriminatorSchema); |
| | 0 | 123 | | } |
| | | 124 | | |
| | 0 | 125 | | JsonTypeInfo derivedTypeInfo = typeInfo.Options.GetTypeInfoInternal(derivedType.DerivedType); |
| | | 126 | | |
| | 0 | 127 | | state.PushSchemaNode(anyOf.Count.ToString(CultureInfo.InvariantCulture)); |
| | 0 | 128 | | JsonSchema derivedSchema = MapJsonSchemaCore( |
| | 0 | 129 | | ref state, |
| | 0 | 130 | | derivedTypeInfo, |
| | 0 | 131 | | parentPolymorphicTypeInfo: typeInfo, |
| | 0 | 132 | | typeDiscriminator: derivedTypeDiscriminator, |
| | 0 | 133 | | parentPolymorphicTypeContainsTypesWithoutDiscriminator: containsTypesWithoutDiscriminator, |
| | 0 | 134 | | parentPolymorphicTypeIsNonNullable: propertyInfo is { IsGetNullable: false, IsSetNullable: false |
| | 0 | 135 | | cacheResult: false); |
| | | 136 | | |
| | 0 | 137 | | state.PopSchemaNode(); |
| | | 138 | | |
| | | 139 | | // Determine if all derived schemas have the same type. |
| | 0 | 140 | | if (anyOf.Count == 0) |
| | 0 | 141 | | { |
| | 0 | 142 | | schemaType = derivedSchema.Type; |
| | 0 | 143 | | } |
| | 0 | 144 | | else if (schemaType != derivedSchema.Type) |
| | 0 | 145 | | { |
| | 0 | 146 | | schemaType = JsonSchemaType.Any; |
| | 0 | 147 | | } |
| | | 148 | | |
| | 0 | 149 | | anyOf.Add(derivedSchema); |
| | 0 | 150 | | } |
| | | 151 | | |
| | 0 | 152 | | state.PopSchemaNode(); |
| | | 153 | | |
| | 0 | 154 | | if (schemaType is not JsonSchemaType.Any) |
| | 0 | 155 | | { |
| | | 156 | | // If all derived types have the same schema type, we can simplify the schema |
| | | 157 | | // by moving the type keyword to the base schema and removing it from the derived schemas. |
| | 0 | 158 | | foreach (JsonSchema derivedSchema in anyOf) |
| | 0 | 159 | | { |
| | 0 | 160 | | derivedSchema.Type = JsonSchemaType.Any; |
| | | 161 | | |
| | 0 | 162 | | if (derivedSchema.KeywordCount == 0) |
| | 0 | 163 | | { |
| | | 164 | | // if removing the type results in an empty schema, |
| | | 165 | | // remove the anyOf array entirely since it's always true. |
| | 0 | 166 | | anyOf = null; |
| | 0 | 167 | | break; |
| | | 168 | | } |
| | 0 | 169 | | } |
| | 0 | 170 | | } |
| | | 171 | | |
| | 0 | 172 | | return CompleteSchema(ref state, new() |
| | 0 | 173 | | { |
| | 0 | 174 | | Type = schemaType, |
| | 0 | 175 | | AnyOf = anyOf, |
| | 0 | 176 | | // If all derived types have a discriminator, we can require it in the base schema. |
| | 0 | 177 | | Required = containsTypesWithoutDiscriminator ? null : [typeDiscriminatorKey] |
| | 0 | 178 | | }); |
| | | 179 | | } |
| | | 180 | | |
| | 0 | 181 | | if (effectiveConverter.NullableElementConverter is { } elementConverter) |
| | 0 | 182 | | { |
| | 0 | 183 | | JsonTypeInfo elementTypeInfo = typeInfo.Options.GetTypeInfo(elementConverter.Type!); |
| | 0 | 184 | | schema = MapJsonSchemaCore(ref state, elementTypeInfo, customConverter: elementConverter, customNumberHa |
| | | 185 | | |
| | 0 | 186 | | if (elementConverter.IsIeeeFloatingPointConverter && |
| | 0 | 187 | | (effectiveNumberHandling & JsonNumberHandling.AllowNamedFloatingPointLiterals) != 0) |
| | 0 | 188 | | { |
| | | 189 | | // IEEE floating-point types with AllowNamedFloatingPointLiterals generate an anyOf schema. |
| | | 190 | | // Fold null into the numeric branch to preserve nullability for nullable wrappers. |
| | 0 | 191 | | Debug.Assert(schema.AnyOf is not null, "IEEE floating-point types with AllowNamedFloatingPointLitera |
| | | 192 | | |
| | 0 | 193 | | List<JsonSchema> anyOf = schema.AnyOf; |
| | 0 | 194 | | Debug.Assert(anyOf.Exists(b => (b.Type & JsonSchemaType.Number) != 0), |
| | 0 | 195 | | "IEEE floating-point anyOf schema should have a numeric branch."); |
| | | 196 | | |
| | 0 | 197 | | foreach (JsonSchema branch in anyOf) |
| | 0 | 198 | | { |
| | 0 | 199 | | if ((branch.Type & JsonSchemaType.Number) != 0) |
| | 0 | 200 | | { |
| | 0 | 201 | | branch.Type |= JsonSchemaType.Null; |
| | 0 | 202 | | break; |
| | | 203 | | } |
| | 0 | 204 | | } |
| | 0 | 205 | | } |
| | 0 | 206 | | else if (schema.Enum is not null) |
| | 0 | 207 | | { |
| | 0 | 208 | | Debug.Assert(elementTypeInfo.Type.IsEnum, "The enum keyword should only be populated by schemas for |
| | 0 | 209 | | schema.Enum.Add(null); // Append null to the enum array. |
| | 0 | 210 | | } |
| | | 211 | | |
| | 0 | 212 | | return CompleteSchema(ref state, schema); |
| | | 213 | | } |
| | | 214 | | |
| | 0 | 215 | | switch (typeInfo.Kind) |
| | | 216 | | { |
| | | 217 | | case JsonTypeInfoKind.Object: |
| | 0 | 218 | | List<KeyValuePair<string, JsonSchema>>? properties = null; |
| | 0 | 219 | | List<string>? required = null; |
| | 0 | 220 | | JsonSchema? additionalProperties = null; |
| | | 221 | | |
| | 0 | 222 | | if (typeInfo.EffectiveUnmappedMemberHandling is JsonUnmappedMemberHandling.Disallow) |
| | 0 | 223 | | { |
| | 0 | 224 | | additionalProperties = JsonSchema.CreateFalseSchema(); |
| | 0 | 225 | | } |
| | | 226 | | |
| | 0 | 227 | | if (typeDiscriminator is { } typeDiscriminatorPair) |
| | 0 | 228 | | { |
| | 0 | 229 | | (properties ??= []).Add(typeDiscriminatorPair); |
| | 0 | 230 | | if (parentPolymorphicTypeContainsTypesWithoutDiscriminator) |
| | 0 | 231 | | { |
| | | 232 | | // Require the discriminator here since it's not common to all derived types. |
| | 0 | 233 | | (required ??= []).Add(typeDiscriminatorPair.Key); |
| | 0 | 234 | | } |
| | 0 | 235 | | } |
| | | 236 | | |
| | 0 | 237 | | state.PushSchemaNode(JsonSchema.PropertiesPropertyName); |
| | 0 | 238 | | foreach (JsonPropertyInfo property in typeInfo.Properties) |
| | 0 | 239 | | { |
| | 0 | 240 | | if (property is { Get: null, Set: null } or { IsExtensionData: true }) |
| | 0 | 241 | | { |
| | 0 | 242 | | continue; // Skip JsonIgnored properties and extension data |
| | | 243 | | } |
| | | 244 | | |
| | 0 | 245 | | state.PushSchemaNode(property.Name); |
| | 0 | 246 | | JsonSchema propertySchema = MapJsonSchemaCore( |
| | 0 | 247 | | ref state, |
| | 0 | 248 | | property.JsonTypeInfo, |
| | 0 | 249 | | propertyInfo: property, |
| | 0 | 250 | | customConverter: property.EffectiveConverter, |
| | 0 | 251 | | customNumberHandling: property.EffectiveNumberHandling); |
| | | 252 | | |
| | 0 | 253 | | state.PopSchemaNode(); |
| | | 254 | | |
| | 0 | 255 | | if (property.AssociatedParameter is { HasDefaultValue: true } parameterInfo) |
| | 0 | 256 | | { |
| | 0 | 257 | | JsonSchema.EnsureMutable(ref propertySchema); |
| | 0 | 258 | | propertySchema.DefaultValue = JsonSerializer.SerializeToNode(parameterInfo.EffectiveDefaultV |
| | 0 | 259 | | propertySchema.HasDefaultValue = true; |
| | 0 | 260 | | } |
| | | 261 | | |
| | 0 | 262 | | (properties ??= []).Add(new(property.Name, propertySchema)); |
| | | 263 | | |
| | | 264 | | // Mark as required if either the property is required or the associated constructor parameter i |
| | | 265 | | // While the latter implies the former in cases where the JsonSerializerOptions.RespectRequiredC |
| | | 266 | | // setting has been enabled, for the case of the schema exporter we always mark non-optional con |
| | 0 | 267 | | if (property is { IsRequired: true } or { AssociatedParameter.IsRequiredParameter: true }) |
| | 0 | 268 | | { |
| | 0 | 269 | | (required ??= []).Add(property.Name); |
| | 0 | 270 | | } |
| | 0 | 271 | | } |
| | | 272 | | |
| | 0 | 273 | | state.PopSchemaNode(); |
| | 0 | 274 | | return CompleteSchema(ref state, new() |
| | 0 | 275 | | { |
| | 0 | 276 | | Type = JsonSchemaType.Object, |
| | 0 | 277 | | Properties = properties, |
| | 0 | 278 | | Required = required, |
| | 0 | 279 | | AdditionalProperties = additionalProperties, |
| | 0 | 280 | | }); |
| | | 281 | | |
| | | 282 | | case JsonTypeInfoKind.Enumerable: |
| | 0 | 283 | | Debug.Assert(typeInfo.ElementTypeInfo is not null); |
| | | 284 | | |
| | 0 | 285 | | if (typeDiscriminator is null) |
| | 0 | 286 | | { |
| | 0 | 287 | | state.PushSchemaNode(JsonSchema.ItemsPropertyName); |
| | 0 | 288 | | JsonSchema items = MapJsonSchemaCore(ref state, typeInfo.ElementTypeInfo, customNumberHandling: |
| | 0 | 289 | | state.PopSchemaNode(); |
| | | 290 | | |
| | 0 | 291 | | return CompleteSchema(ref state, new() |
| | 0 | 292 | | { |
| | 0 | 293 | | Type = JsonSchemaType.Array, |
| | 0 | 294 | | Items = items.IsTrue ? null : items, |
| | 0 | 295 | | }); |
| | | 296 | | } |
| | | 297 | | else |
| | 0 | 298 | | { |
| | | 299 | | // Polymorphic enumerable types are represented using a wrapping object: |
| | | 300 | | // { "$type" : "discriminator", "$values" : [element1, element2, ...] } |
| | | 301 | | // Which corresponds to the schema |
| | | 302 | | // { "properties" : { "$type" : { "const" : "discriminator" }, "$values" : { "type" : "array", " |
| | | 303 | | const string ValuesKeyword = JsonSerializer.ValuesPropertyName; |
| | | 304 | | |
| | 0 | 305 | | state.PushSchemaNode(JsonSchema.PropertiesPropertyName); |
| | 0 | 306 | | state.PushSchemaNode(ValuesKeyword); |
| | 0 | 307 | | state.PushSchemaNode(JsonSchema.ItemsPropertyName); |
| | | 308 | | |
| | 0 | 309 | | JsonSchema items = MapJsonSchemaCore(ref state, typeInfo.ElementTypeInfo, customNumberHandling: |
| | | 310 | | |
| | 0 | 311 | | state.PopSchemaNode(); |
| | 0 | 312 | | state.PopSchemaNode(); |
| | 0 | 313 | | state.PopSchemaNode(); |
| | | 314 | | |
| | 0 | 315 | | return CompleteSchema(ref state, new() |
| | 0 | 316 | | { |
| | 0 | 317 | | Type = JsonSchemaType.Object, |
| | 0 | 318 | | Properties = |
| | 0 | 319 | | [ |
| | 0 | 320 | | typeDiscriminator.Value, |
| | 0 | 321 | | new(ValuesKeyword, |
| | 0 | 322 | | new JsonSchema() |
| | 0 | 323 | | { |
| | 0 | 324 | | Type = JsonSchemaType.Array, |
| | 0 | 325 | | Items = items.IsTrue ? null : items, |
| | 0 | 326 | | }), |
| | 0 | 327 | | ], |
| | 0 | 328 | | Required = parentPolymorphicTypeContainsTypesWithoutDiscriminator ? [typeDiscriminator.Value |
| | 0 | 329 | | }); |
| | | 330 | | } |
| | | 331 | | |
| | | 332 | | case JsonTypeInfoKind.Dictionary: |
| | 0 | 333 | | Debug.Assert(typeInfo.ElementTypeInfo is not null); |
| | | 334 | | |
| | 0 | 335 | | List<KeyValuePair<string, JsonSchema>>? dictProps = null; |
| | 0 | 336 | | List<string>? dictRequired = null; |
| | | 337 | | |
| | 0 | 338 | | if (typeDiscriminator is { } dictDiscriminator) |
| | 0 | 339 | | { |
| | 0 | 340 | | dictProps = [dictDiscriminator]; |
| | 0 | 341 | | if (parentPolymorphicTypeContainsTypesWithoutDiscriminator) |
| | 0 | 342 | | { |
| | | 343 | | // Require the discriminator here since it's not common to all derived types. |
| | 0 | 344 | | dictRequired = [dictDiscriminator.Key]; |
| | 0 | 345 | | } |
| | 0 | 346 | | } |
| | | 347 | | |
| | 0 | 348 | | state.PushSchemaNode(JsonSchema.AdditionalPropertiesPropertyName); |
| | 0 | 349 | | JsonSchema valueSchema = MapJsonSchemaCore(ref state, typeInfo.ElementTypeInfo, customNumberHandling |
| | 0 | 350 | | state.PopSchemaNode(); |
| | | 351 | | |
| | 0 | 352 | | return CompleteSchema(ref state, new() |
| | 0 | 353 | | { |
| | 0 | 354 | | Type = JsonSchemaType.Object, |
| | 0 | 355 | | Properties = dictProps, |
| | 0 | 356 | | Required = dictRequired, |
| | 0 | 357 | | AdditionalProperties = valueSchema.IsTrue ? null : valueSchema, |
| | 0 | 358 | | }); |
| | | 359 | | |
| | | 360 | | case JsonTypeInfoKind.Union: |
| | 0 | 361 | | if (typeInfo.UnionCases is { Count: > 0 } unionCases) |
| | 0 | 362 | | { |
| | 0 | 363 | | JsonSchemaType unionSchemaType = JsonSchemaType.Any; |
| | 0 | 364 | | List<JsonSchema>? unionAnyOf = new(unionCases.Count); |
| | | 365 | | |
| | 0 | 366 | | state.PushSchemaNode(JsonSchema.AnyOfPropertyName); |
| | | 367 | | |
| | 0 | 368 | | foreach (JsonUnionCaseInfo caseInfo in unionCases) |
| | 0 | 369 | | { |
| | 0 | 370 | | JsonTypeInfo caseTypeInfo = typeInfo.Options.GetTypeInfoInternal(caseInfo.CaseType); |
| | | 371 | | |
| | 0 | 372 | | state.PushSchemaNode(unionAnyOf.Count.ToString(CultureInfo.InvariantCulture)); |
| | 0 | 373 | | JsonSchema caseSchema = MapJsonSchemaCore(ref state, caseTypeInfo, customNumberHandling: typ |
| | 0 | 374 | | state.PopSchemaNode(); |
| | | 375 | | |
| | 0 | 376 | | if (caseInfo.IsNullable) |
| | 0 | 377 | | { |
| | 0 | 378 | | caseSchema.Type |= JsonSchemaType.Null; |
| | 0 | 379 | | } |
| | | 380 | | |
| | 0 | 381 | | if (unionAnyOf.Count == 0) |
| | 0 | 382 | | { |
| | 0 | 383 | | unionSchemaType = caseSchema.Type; |
| | 0 | 384 | | } |
| | 0 | 385 | | else if (unionSchemaType != caseSchema.Type) |
| | 0 | 386 | | { |
| | 0 | 387 | | unionSchemaType = JsonSchemaType.Any; |
| | 0 | 388 | | } |
| | | 389 | | |
| | 0 | 390 | | unionAnyOf.Add(caseSchema); |
| | 0 | 391 | | } |
| | | 392 | | |
| | 0 | 393 | | state.PopSchemaNode(); |
| | | 394 | | |
| | 0 | 395 | | if (unionSchemaType is not JsonSchemaType.Any) |
| | 0 | 396 | | { |
| | 0 | 397 | | foreach (JsonSchema caseSchema in unionAnyOf) |
| | 0 | 398 | | { |
| | 0 | 399 | | caseSchema.Type = JsonSchemaType.Any; |
| | | 400 | | |
| | 0 | 401 | | if (caseSchema.KeywordCount == 0) |
| | 0 | 402 | | { |
| | 0 | 403 | | unionAnyOf = null; |
| | 0 | 404 | | break; |
| | | 405 | | } |
| | 0 | 406 | | } |
| | 0 | 407 | | } |
| | | 408 | | |
| | 0 | 409 | | return CompleteSchema(ref state, new() |
| | 0 | 410 | | { |
| | 0 | 411 | | Type = unionSchemaType, |
| | 0 | 412 | | AnyOf = unionAnyOf, |
| | 0 | 413 | | }); |
| | | 414 | | } |
| | | 415 | | |
| | 0 | 416 | | return CompleteSchema(ref state, JsonSchema.CreateTrueSchema()); |
| | | 417 | | |
| | | 418 | | default: |
| | 0 | 419 | | Debug.Assert(typeInfo.Kind is JsonTypeInfoKind.None); |
| | | 420 | | // Return a `true` schema for types with user-defined converters. |
| | 0 | 421 | | return CompleteSchema(ref state, JsonSchema.CreateTrueSchema()); |
| | | 422 | | } |
| | | 423 | | |
| | | 424 | | JsonSchema CompleteSchema(ref GenerationState state, JsonSchema schema) |
| | 0 | 425 | | { |
| | 0 | 426 | | if (HasObsoleteAttribute(typeInfo.Type) || |
| | 0 | 427 | | HasObsoleteAttribute(propertyInfo?.AttributeProvider)) |
| | 0 | 428 | | { |
| | 0 | 429 | | JsonSchema.EnsureMutable(ref schema); |
| | 0 | 430 | | schema.Deprecated = true; |
| | 0 | 431 | | } |
| | | 432 | | |
| | 0 | 433 | | if (schema.Ref is null) |
| | 0 | 434 | | { |
| | 0 | 435 | | if (IsNullableSchema(state.ExporterOptions)) |
| | 0 | 436 | | { |
| | 0 | 437 | | schema.MakeNullable(); |
| | 0 | 438 | | } |
| | | 439 | | |
| | | 440 | | bool IsNullableSchema(JsonSchemaExporterOptions options) |
| | 0 | 441 | | { |
| | | 442 | | // A schema is marked as nullable if either: |
| | | 443 | | // 1. We have a schema for a property where either the getter or setter are marked as nullable. |
| | | 444 | | // 2. We have a schema for a Nullable<T> type. |
| | | 445 | | // 3. We have a schema for a reference type, unless we're explicitly treating null-oblivious typ |
| | | 446 | | |
| | 0 | 447 | | if (propertyInfo is not null) |
| | 0 | 448 | | { |
| | 0 | 449 | | if (propertyInfo.Get is not null && propertyInfo.IsGetNullable) |
| | 0 | 450 | | { |
| | 0 | 451 | | return true; |
| | | 452 | | } |
| | | 453 | | |
| | 0 | 454 | | if (propertyInfo.AssociatedParameter is not null) |
| | 0 | 455 | | { |
| | 0 | 456 | | return propertyInfo.AssociatedParameter.IsNullable; |
| | | 457 | | } |
| | | 458 | | |
| | 0 | 459 | | return propertyInfo.Set is not null && propertyInfo.IsSetNullable; |
| | | 460 | | } |
| | | 461 | | |
| | 0 | 462 | | if (typeInfo.IsNullable) |
| | 0 | 463 | | { |
| | 0 | 464 | | return true; |
| | | 465 | | } |
| | | 466 | | |
| | 0 | 467 | | return !typeInfo.Type.IsValueType && !parentPolymorphicTypeIsNonNullable && !options.TreatNullOb |
| | 0 | 468 | | } |
| | 0 | 469 | | } |
| | | 470 | | |
| | 0 | 471 | | if (state.ExporterOptions.TransformSchemaNode is not null) |
| | 0 | 472 | | { |
| | | 473 | | // Prime the schema for invocation by the JsonNode transformer. |
| | 0 | 474 | | schema.ExporterContext = exporterContext; |
| | 0 | 475 | | } |
| | | 476 | | |
| | 0 | 477 | | return schema; |
| | 0 | 478 | | } |
| | 0 | 479 | | } |
| | | 480 | | |
| | | 481 | | private static void ValidateOptions(JsonSerializerOptions options) |
| | 0 | 482 | | { |
| | 0 | 483 | | if (options.ReferenceHandler == ReferenceHandler.Preserve) |
| | 0 | 484 | | { |
| | 0 | 485 | | ThrowHelper.ThrowNotSupportedException_JsonSchemaExporterDoesNotSupportReferenceHandlerPreserve(); |
| | | 486 | | } |
| | | 487 | | |
| | 0 | 488 | | options.MakeReadOnly(); |
| | 0 | 489 | | } |
| | | 490 | | |
| | | 491 | | private static bool HasObsoleteAttribute(ICustomAttributeProvider? attributeProvider) |
| | 0 | 492 | | { |
| | 0 | 493 | | if (attributeProvider is null) |
| | 0 | 494 | | { |
| | 0 | 495 | | return false; |
| | | 496 | | } |
| | | 497 | | |
| | | 498 | | // Identify ObsoleteAttribute using its full type name rather than typeof(ObsoleteAttribute). |
| | | 499 | | // On downlevel targets System.Text.Json compiles in an internal ObsoleteAttribute polyfill |
| | | 500 | | // that would otherwise shadow the framework type, causing the typeof comparison to never match |
| | | 501 | | // the ObsoleteAttribute applied by user code. |
| | 0 | 502 | | foreach (object attribute in attributeProvider.GetCustomAttributes(inherit: true)) |
| | 0 | 503 | | { |
| | 0 | 504 | | if (attribute.GetType().FullName == "System.ObsoleteAttribute") |
| | 0 | 505 | | { |
| | 0 | 506 | | return true; |
| | | 507 | | } |
| | 0 | 508 | | } |
| | | 509 | | |
| | 0 | 510 | | return false; |
| | 0 | 511 | | } |
| | | 512 | | |
| | | 513 | | private static bool IsPolymorphicTypeThatSpecifiesItselfAsDerivedType(JsonTypeInfo typeInfo) |
| | 0 | 514 | | { |
| | 0 | 515 | | Debug.Assert(typeInfo.PolymorphismOptions is not null); |
| | | 516 | | |
| | 0 | 517 | | foreach (JsonDerivedType derivedType in typeInfo.PolymorphismOptions.DerivedTypes) |
| | 0 | 518 | | { |
| | 0 | 519 | | if (derivedType.DerivedType == typeInfo.Type) |
| | 0 | 520 | | { |
| | 0 | 521 | | return true; |
| | | 522 | | } |
| | 0 | 523 | | } |
| | | 524 | | |
| | 0 | 525 | | return false; |
| | 0 | 526 | | } |
| | | 527 | | |
| | | 528 | | private readonly ref struct GenerationState(JsonSerializerOptions options, JsonSchemaExporterOptions exporterOpt |
| | | 529 | | { |
| | 0 | 530 | | private readonly List<string> _currentPath = []; |
| | 0 | 531 | | private readonly Dictionary<(JsonTypeInfo, JsonPropertyInfo?), string[]> _generated = new(); |
| | | 532 | | |
| | 0 | 533 | | public int CurrentDepth => _currentPath.Count; |
| | 0 | 534 | | public JsonSerializerOptions Options { get; } = options; |
| | 0 | 535 | | public JsonSchemaExporterOptions ExporterOptions { get; } = exporterOptions; |
| | | 536 | | |
| | | 537 | | public void PushSchemaNode(string nodeId) |
| | 0 | 538 | | { |
| | 0 | 539 | | if (CurrentDepth == Options.EffectiveMaxDepth) |
| | 0 | 540 | | { |
| | 0 | 541 | | ThrowHelper.ThrowInvalidOperationException_JsonSchemaExporterDepthTooLarge(); |
| | 0 | 542 | | } |
| | | 543 | | |
| | 0 | 544 | | _currentPath.Add(nodeId); |
| | 0 | 545 | | } |
| | | 546 | | |
| | | 547 | | public void PopSchemaNode() |
| | 0 | 548 | | { |
| | 0 | 549 | | Debug.Assert(CurrentDepth > 0); |
| | 0 | 550 | | _currentPath.RemoveAt(_currentPath.Count - 1); |
| | 0 | 551 | | } |
| | | 552 | | |
| | | 553 | | /// <summary> |
| | | 554 | | /// Registers the current schema node generation context; if it has already been generated return a JSON poi |
| | | 555 | | /// </summary> |
| | | 556 | | public bool TryGetExistingJsonPointer(in JsonSchemaExporterContext context, [NotNullWhen(true)] out string? |
| | 0 | 557 | | { |
| | 0 | 558 | | (JsonTypeInfo TypeInfo, JsonPropertyInfo? PropertyInfo) key = (context.TypeInfo, context.PropertyInfo); |
| | | 559 | | #if NET |
| | 0 | 560 | | ref string[]? pathToSchema = ref CollectionsMarshal.GetValueRefOrAddDefault(_generated, key, out bool ex |
| | | 561 | | #else |
| | | 562 | | bool exists = _generated.TryGetValue(key, out string[]? pathToSchema); |
| | | 563 | | #endif |
| | 0 | 564 | | if (exists) |
| | 0 | 565 | | { |
| | 0 | 566 | | existingJsonPointer = FormatJsonPointer(pathToSchema); |
| | 0 | 567 | | return true; |
| | | 568 | | } |
| | | 569 | | #if NET |
| | 0 | 570 | | pathToSchema = context._path; |
| | | 571 | | #else |
| | | 572 | | _generated[key] = context._path; |
| | | 573 | | #endif |
| | 0 | 574 | | existingJsonPointer = null; |
| | 0 | 575 | | return false; |
| | 0 | 576 | | } |
| | | 577 | | |
| | | 578 | | public JsonSchemaExporterContext CreateContext(JsonTypeInfo typeInfo, JsonPropertyInfo? propertyInfo, JsonTy |
| | 0 | 579 | | { |
| | 0 | 580 | | return new JsonSchemaExporterContext(typeInfo, propertyInfo, baseTypeInfo, [.. _currentPath]); |
| | 0 | 581 | | } |
| | | 582 | | |
| | | 583 | | private static string FormatJsonPointer(ReadOnlySpan<string> path) |
| | 0 | 584 | | { |
| | 0 | 585 | | if (path.IsEmpty) |
| | 0 | 586 | | { |
| | 0 | 587 | | return "#"; |
| | | 588 | | } |
| | | 589 | | |
| | 0 | 590 | | using ValueStringBuilder sb = new(initialCapacity: path.Length * 10); |
| | 0 | 591 | | sb.Append('#'); |
| | | 592 | | |
| | 0 | 593 | | foreach (string segment in path) |
| | 0 | 594 | | { |
| | 0 | 595 | | sb.Append('/'); |
| | | 596 | | |
| | | 597 | | // Per RFC 6901 the characters '~' and '/' are escaped as '~0' and '~1'. |
| | 0 | 598 | | string escapedToken = segment.Replace("~", "~0").Replace("/", "~1"); |
| | | 599 | | |
| | | 600 | | // Per RFC 6901 section 6 the JSON Pointer is embedded in a URI fragment, |
| | | 601 | | // so percent-encode any characters that are not valid in a URI fragment. |
| | 0 | 602 | | sb.Append(Uri.EscapeDataString(escapedToken)); |
| | 0 | 603 | | } |
| | | 604 | | |
| | 0 | 605 | | return sb.ToString(); |
| | 0 | 606 | | } |
| | | 607 | | } |
| | | 608 | | } |
| | | 609 | | } |
| | | 610 | | |