Sdílet prostřednictvím


Exportér schématu JSON

Třída JsonSchemaExporter představená v .NET 9 umožňuje extrahovat dokumenty schématu JSON z typů .NET pomocí instance JsonSerializerOptions nebo JsonTypeInfo instance. Výsledné schéma poskytuje specifikaci kontraktu serializace JSON pro typ .NET. Schéma popisuje tvar toho, co by bylo serializováno a co může být deserializováno.

Následující fragment kódu ukazuje příklad.

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);

Jak je vidět v tomto příkladu, vývozce rozlišuje mezi vlastnostmi s možnou hodnotou null a nenulovou hodnotou a naplní required klíčové slovo na základě parametru konstruktoru volitelným nebo ne.

Konfigurace výstupu schématu

Výstup schématu můžete ovlivnit konfigurací zadanou v JsonSerializerOptions instanci, JsonTypeInfo pro kterou metodu GetJsonSchemaAsNode voláte. Následující příklad nastaví zásadu pojmenování na KebabCaseUpper, zapisuje čísla jako řetězce a zakáže nemapované vlastnosti.

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; }
}

Vygenerované schéma můžete dále řídit pomocí JsonSchemaExporterOptions typu konfigurace. Následující příklad nastaví TreatNullObliviousAsNonNullable vlastnost tak, aby true označí typy kořenové úrovně jako non-nullable.

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);

Transformace generovaného schématu

Pro vygenerované uzly schématu můžete použít vlastní transformace zadáním delegáta TransformSchemaNode . Následující příklad zahrnuje text z DescriptionAttribute poznámek do generovaného schématu.

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;
    }
};

Následující příklad kódu vygeneruje schéma, které zahrnuje description zdroj klíčových slov z DescriptionAttribute poznámek:

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);