Dela via


JSON-schemaexportör

Med JsonSchemaExporter klassen, som introducerades i .NET 9, kan du extrahera JSON-schemadokument från .NET-typer med hjälp av antingen en instans eller JsonSerializerOptions instansJsonTypeInfo. 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.

Konfigurera schemautdata

Du kan påverka schemautdata efter konfiguration som anges i den JsonSerializerOptions eller-instans JsonTypeInfo som du anropar metoden på GetJsonSchemaAsNode . 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);