Kommentar
Åtkomst till den här sidan kräver auktorisering. Du kan prova att logga in eller ändra kataloger.
Åtkomst till den här sidan kräver auktorisering. Du kan prova att ändra kataloger.
Klassen JsonSchemaExporter, som introducerades i .NET 9, låter dig extrahera JSON-schemadokument från .NET-typer med hjälp av antingen en JsonSerializerOptions eller JsonTypeInfo instans. Det resulterande schemat innehåller en specifikation av JSON-serialiseringskontraktet för .NET-typen. Schemat beskriver formen på vad som skulle serialiseras och vad som kan deserialiseras.
Följande kodfragment visar ett exempel.
public static void SimpleExtraction()
{
JsonSerializerOptions options = JsonSerializerOptions.Default;
JsonNode schema = options.GetJsonSchemaAsNode(typeof(Person));
Console.WriteLine(schema.ToString());
//{
// "type": ["object", "null"],
// "properties": {
// "Name": { "type": "string" },
// "Age": { "type": "integer" },
// "Address": { "type": ["string", "null"], "default": null }
// },
// "required": ["Name", "Age"]
//}
}
record Person(string Name, int Age, string? Address = null);
Som du kan se i det här exemplet skiljer exportören mellan null- och icke-nullbara egenskaper, och det fyller i nyckelordet required på grund av att en konstruktorparameter är valfri eller inte.
Från och med .NET 11 känner exportören igen typerna BFloat16, Decimal32, Decimal64och Decimal128 . Den exporterar scheman för deras nullbara varianter och för namngivna literaler när du aktiverar AllowNamedFloatingPointLiterals.
Scheman för unionstyper
Från och med .NET 11 beskriver JsonSchemaExporter en C#-union med ett otaggat anyOf-schema som har en gren för varje fall. Unionen lägger inte till någon diskriminator eftersom JsonSerializer bara skriver det aktiva fallet. När du däremot aktiverar inferens för en sluten hierarki, innehåller JSON som serialiseras som den slutna bastypen en $type diskriminator som identifierar den härledda typen. Det anyOf som beskrivs här är JsonSchemaExporter utdata; ASP.NET Core genererar OpenAPI-dokument separat.
Konfigurera schemautdata
Du kan påverka schemautdata genom den konfiguration som anges i antingen JsonSerializerOptions- eller JsonTypeInfo-instansen som du anropar GetJsonSchemaAsNode-metoden på. I följande exempel anges namngivningsprincipen till KebabCaseUpper, skriver tal som strängar och tillåter inte ommappade egenskaper.
public static void CustomExtraction()
{
JsonSerializerOptions options = new(JsonSerializerOptions.Default)
{
PropertyNamingPolicy = JsonNamingPolicy.KebabCaseUpper,
NumberHandling = JsonNumberHandling.WriteAsString,
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
};
JsonNode schema = options.GetJsonSchemaAsNode(typeof(MyPoco));
Console.WriteLine(schema.ToString());
//{
// "type": ["object", "null"],
// "properties": {
// "NUMERIC-VALUE": {
// "type": ["string", "integer"],
// "pattern": "^-?(?:0|[1-9]\\d*)$"
// }
// },
// "additionalProperties": false
//}
}
class MyPoco
{
public int NumericValue { get; init; }
}
Du kan styra det genererade schemat ytterligare med hjälp av konfigurationstypen JsonSchemaExporterOptions . I följande exempel anges TreatNullObliviousAsNonNullable egenskapen till true för att markera typer på rotnivå som icke-nullbara.
public static void CustomExtraction()
{
JsonSerializerOptions options = JsonSerializerOptions.Default;
JsonSchemaExporterOptions exporterOptions = new()
{
TreatNullObliviousAsNonNullable = true,
};
JsonNode schema = options.GetJsonSchemaAsNode(typeof(Person), exporterOptions);
Console.WriteLine(schema.ToString());
//{
// "type": "object",
// "properties": {
// "Name": { "type": "string" }
// },
// "required": ["Name"]
//}
}
record Person(string Name);
Transformera det genererade schemat
Du kan använda dina egna transformeringar för genererade schemanoder genom att ange ett TransformSchemaNode ombud. I följande exempel ingår text från DescriptionAttribute anteckningar i det genererade schemat.
JsonSchemaExporterOptions exporterOptions = new()
{
TransformSchemaNode = (context, schema) =>
{
// Determine if a type or property and extract the relevant attribute provider.
ICustomAttributeProvider? attributeProvider = context.PropertyInfo is not null
? context.PropertyInfo.AttributeProvider
: context.TypeInfo.Type;
// Look up any description attributes.
DescriptionAttribute? descriptionAttr = attributeProvider?
.GetCustomAttributes(inherit: true)
.Select(attr => attr as DescriptionAttribute)
.FirstOrDefault(attr => attr is not null);
// Apply description attribute to the generated schema.
if (descriptionAttr != null)
{
if (schema is not JsonObject jObj)
{
// Handle the case where the schema is a Boolean.
JsonValueKind valueKind = schema.GetValueKind();
Debug.Assert(valueKind is JsonValueKind.True or JsonValueKind.False);
schema = jObj = new JsonObject();
if (valueKind is JsonValueKind.False)
{
jObj.Add("not", true);
}
}
jObj.Insert(0, "description", descriptionAttr.Description);
}
return schema;
}
};
Följande kodexempel genererar ett schema som innehåller nyckelordskälla description från DescriptionAttribute anteckningar:
JsonSerializerOptions options = JsonSerializerOptions.Default;
JsonNode schema = options.GetJsonSchemaAsNode(typeof(Person), exporterOptions);
Console.WriteLine(schema.ToString());
//{
// "description": "A person",
// "type": ["object", "null"],
// "properties": {
// "Name": { "description": "The name of the person", "type": "string" }
// },
// "required": ["Name"]
//}
[Description("A person")]
record Person([property: Description("The name of the person")] string Name);