Search code examples
c#jsonjsonschemajson-everything

How to make members with the required keyword (C# 11) be required in JSON schemas generated by json-schema builder?


I've been exploring the use of C# 11’s required members feature in conjunction with JSON schema generation. Specifically, I'm using the JsonSchemaBuilder class (from the JsonEverything library) to generate JSON Schemas, and I’m wondering if there are any plans or timelines for supporting the C# 11 required members feature.

At the moment, C# 11’s required keyword ensures that certain properties must be initialized. I’m hoping that this concept could be integrated into JsonSchemaBuilder so that the generated schema automatically reflects these requirements (e.g., by adding properties to the schema’s required list).

I’ve looked through the GitHub issues and discussions for JsonEverything but haven’t found any mention of this. Is there a recommended workaround or approach to achieve this behavior right now?

Any insights or pointers would be greatly appreciated.

I’ve experimented with marking class properties as required in C# 11 and then generating JSON Schemas using JsonSchemaBuilder. I expected that properties marked as required would automatically appear in the schema’s required array. However, this doesn’t seem to happen out of the box.

What we want:

public class A
{
  public required string Name { Get; Set;}
}

Instead of:

public class A
{
  [Required]
  public required string Name { Get; Set;}
}

To have this property as required in the Json Schema

PD: This question is new and different from C# 11 - detect required property by reflection because nowadays there is a way to know if the property is required, an example:

using System;
using System.Reflection;
using System.Runtime.CompilerServices;

public class Example
{
    public required string RequiredProperty { get; set; }
}

public class Program
{
    public static void Main()
    {
        var prop = typeof(Example).GetProperty("RequiredProperty");
        bool isRequired = prop.IsDefined(typeof(RequiredMemberAttribute));
        Console.WriteLine(isRequired); // Imprimirá "True"
    }
}

How we are building the JsonSchema:

var schema = new JsonSchemaBuilder()
    .Schema("http://json-schema.org/draft-07/schema#")
    .Title({title})
    .Description({description})
    .FromType(type)
    .Build();

Solution

  • Short answer is it's not supported currently.

    Longer answer is I have a PR set up specifically for this, but there are still issues that I haven't had time to address.

    PR: https://github.com/json-everything/json-everything/pull/817