0

I have the following classes:

public class ScheduledTask
{       
    public Frequency Frequency { get; set; }
    public DateTime LastRun { get; set; }
    public string Status { get; set; }
}

Frequency class:

[BsonDiscriminator(RootClass = true)]
[BsonKnownTypes(typeof(Once), typeof(Daily))]
public class Frequency
{
    public Frequency(TimeSpan hour)
    {
        Hour = hour;
    }
    public TimeSpan Hour { get; set; }
}

public class Once : Frequency
{
    public Once(TimeSpan time, DateTime date) : base(time)
    {
        Date = Date;
    }
    public DateTime Date { get; set; }
}
public class Daily : Frequency
{
    public Daily(TimeSpan time) : base(time)
    {

    }
}

I'm sending this json to my WebApi:

{
  "Frequency": {
  "$type": "setupsaver_api.Models.TeamManagement.Once, setupsaver-api",
  "Date": "2021-01-01T00:00:00Z",
  "Hour": "07:00:00"
},
"LastRun": "2021-01-01T00:00:00Z",
"Status": null
} 

API:

    [HttpPost]
    [Route("SaveTask")]
    public IHttpActionResult SaveTask([FromBody] JObject task)
    {
            ScheduledTask scheduledTask = ConvertJobjectToScheduledTask(task);
            return Ok();
    }

    private static ScheduledTask ConvertJobjectToScheduledTask(JObject task)
    {
        var scheduledTask = JsonConvert.DeserializeObject<ScheduledTask>(task.ToString(), new JsonSerializerSettings
        {
            DateFormatHandling = DateFormatHandling.IsoDateFormat,
            TypeNameHandling = TypeNameHandling.Auto
        });
        return scheduledTask;
    }

After deserialization, scheduledTask.Frequency.Date failed to be parsed and it is set to the default date time:"0001-01-01T00:00:00Z". (scheduledTask.LastRun is parsed successfully)

I would really appreciate helping me to figure this problem out!! Thanks in advance

user13982200
  • 13
  • 1
  • 5
  • Did you get any exceptions? Are any of the properties get properly deserialized? the names of the json properties and the names of the class properties should be the same or an attribute needs to be added to the c# classes to indicate the differences between the json names and the class property names. – jdweng Jan 14 '21 at 11:21
  • I don't get and exception only the scheduledTask.Frequency.Date is set to the default dateTime value instead of the given value, about the names, there are the same in the json and classes, isn't it? – user13982200 Jan 14 '21 at 11:31
  • That is what you would get if the names in the json are not the same as the names in the c# classes. Do ANY of the other properties deserialize properly? – jdweng Jan 14 '21 at 11:36
  • All the other properties deserialize properly – user13982200 Jan 14 '21 at 11:40

0 Answers0