0

I have a class that is used for collection responses:

public class CollectionResponse<T>
{
    [JsonExtensionData]
    public Dictionary<string, object> Items { get; } = new(1);

    public CollectionResponse(string name, IEnumerable<T> objects)
    {
        Items.Add(name, objects);
    }
}

[JsonExtensionData] perfectly helps with having a dynamic name for different response types. However, I need to set [Required] annotation for that extended data to reflect it in OpenApi schema.

new CollectionResponse<Car>("cars", new [] {new Car()});

should result in OpenApi schema:

"CarCollectionResponse": {
        "required": [
          "cars"
        ],
        "type": "object",
        "properties": {
          "cars": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Car"
            },
            "readOnly": true
          }
        }
      }

So, question is, how to maintain a dynamic property name while also setting it as [Required]?

convexmethod
  • 264
  • 2
  • 8
  • It looks like you are using System.Text.Json. This serializer does not support `[Required]` annotations, see [Compare Newtonsoft.Json to System.Text.Json, and migrate to System.Text.Json: Required properties](https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to#required-properties) and [Does the new `System.Text.Json` have a required property attribute?](https://stackoverflow.com/q/58443181) for confirmation. The suggested workaround is to manually check for the required property in a converter, and throw an exception if not present. – dbc Mar 21 '22 at 13:39
  • Also, can you please explain what you mean by *However, I need to set `[Required]` annotation for that extended data*? Extension data is by definition free-form. There are no properties to which to apply annotations. Can you [edit] your question to share a [mcve] showing what you want to do? – dbc Mar 21 '22 at 13:41
  • Instead of posting the code that hard to read , it is better for you to post a Json you have and a json you need. – Serge Mar 21 '22 at 13:45
  • Thanks guys for quick comments, specified my question with more focusing on my required result rather than `thoughts` – convexmethod Mar 21 '22 at 14:10
  • I suspect there is no way to do what you want automatically, because the schema is generated from compile-time attributes and, in your example, the property name `"cars"` is entirely runtime. And, of course, a `Dictionary` has no compile-time type information from which to generate a schema for its values. – dbc Mar 21 '22 at 14:48
  • Why are you even using an untyped data model like `public Dictionary Items`? If you used a fully typed data model (E.g. `public class CarResponse { [Required] public List Cars { get; set; } = new (); }`) the schema would be generated automatically. – dbc Mar 21 '22 at 15:04

0 Answers0