3

I get this object specification in (OpenApi 3.0.1) from a vendor:

"ExampleTO" : {
  "codeValidFrom" : {
    "type" : "string",
    "format" : "date"
  }
}

NSwag generates this property in a C# client (correctly, I think):

[Newtonsoft.Json.JsonProperty("codeValidFrom",
 Required = Newtonsoft.Json.Required.DisallowNull,
 NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
[Newtonsoft.Json.JsonConverter(typeof(DateFormatConverter))]
public System.DateTimeOffset CodeValidFrom { get; set; }

Problem: there are null values in "codeValidFrom". I think the specification should look like:

"ExampleTO" : {
  "codeValidFrom" : {
    "type" : "string",
    "format" : "date",
    "nullable: "true"
  }
}

The vendor does not want to make this addition, claiming that the schema is generated and cannot be easily changed.

Is there a way to still make this work with an NSwag client? Ideally, I would make all string properties nullable.

TvdH
  • 896
  • 10
  • 27

1 Answers1

1

I encountered a similar problem with a third party API that lies about the nullability of its properties. I'm using a client generator that I wrote myself, so I gave it an option to use a schema visitor (discussed in issue #1814 as a solution to a different problem) to clear the "required" property collection of the Swagger document, thereby making all properties default to nullable. You could probably achieve the same thing by manipulating the JSON before parsing it.

class RequiredVisitor : JsonSchemaVisitorBase
{
    protected override Task<JsonSchema4> VisitSchemaAsync(JsonSchema4 schema, string path, string typeNameHint)
    {
        schema.RequiredProperties.Clear();
        return Task.FromResult(schema);
    }
}

Use it like this (not quite verbatim from my code, untested):

var doc = await SwaggerDocument.FromJsonAsync(json);
await new RequiredVisitor().VisitAsync(doc);
StackOverthrow
  • 841
  • 8
  • 18