villuMal
villuMal

Reputation: 43

Annotate Format on Properties for JSchema Generation

I am using Newtonsoft.Json.Schema to generate schemas. One of the properties of a class I have is DateTime but we only care about the Date component of the property. I have added a JsonConverter to handle that. So the Json is getting converted properly but fails during schema valiation because of the date format.

My class looks like

[DataContract]
public class SomeClass
{
   [DataMember]
   [JsonProperty("someDate")]
   [JsonConverter(typeof(ShortDateConverter))]
   public DateTime SomeDate { get; set; }
}


public class ShortDateConverter : IsoDateTimeConverter
{
    public ShortDateConverter()
    {
        base.DateTimeFormat = "yyyy-MM-dd";
    }
}

When JSchemaGenerator generates it the output looks like this

{
  "definitions": {
    "SomeClass": {
      "type": [
        "object",
        "null"
      ],
      "properties": {
        "someDate": {
          "type": "string",
          "format": "date-time"
        }
      }
    }
  }
}

But I want the format to be date, something like this

    {
  "definitions": {
    "SomeClass": {
      "type": [
        "object",
        "null"
      ],
      "properties": {
        "someDate": {
          "type": "string",
          "format": "date"
        }
      }
    }
  }
}

Is it possible using any supported annotations?

[DataContract]
public class SomeClass
{
   [DataMember]
   [JsonProperty("someDate")]
   [JsonConverter(typeof(ShortDateConverter))]
   [Format("date")]
   [JSchema(Format = "date"]
   public DateTime SomeDate { get; set; }
}

Upvotes: 1

Views: 725

Answers (1)

Evk
Evk

Reputation: 101493

Yes it's possible with DataTypeAttribute:

[DataContract]
public class SomeClass
{
    [DataMember]
    [JsonProperty("someDate")]
    [JsonConverter(typeof(ShortDateConverter))]       
    [System.ComponentModel.DataAnnotations.DataType(DataType.Date)]
    public DateTime SomeDate { get; set; }
}

Upvotes: 2

Related Questions