Home > database >  Want to pass empty string in datetime field in c#
Want to pass empty string in datetime field in c#

Time:01-11

I am passing empty value in json payload in datetime field. Below is json payload example.

Here in dateOf in Loans2021 I am passing ""

{
    "isCompany": null,
    "Loans2020": {
        "dateOf": "2022-12-31T19:00:00.000Z",
        "Amount": 1000,
    },
    "Loans2021": {
        "Amount": 0,
        "dateOf": ""
    }
}

I am getting error as per below.

"errors": {
    "request": [
      "The request field is required."
    ],
    "$.Loans2021.dateOn": [
      "The JSON value could not be converted to System.Nullable`1[System.DateTime]. Path:.."
    ]

I want to pass empty string in datetime field so any idea how to do this.

I am using C#, .net core in web api

CodePudding user response:

You can't pass the dateOf in this "" format instead of this pass the dateOf as null.

Try like this

{
"isCompany": null,
"Loans2020": {
    "dateOf": "2022-12-31T19:00:00.000Z",
    "Amount": 1000,
},
"Loans2021": {
    "Amount": 0,
    "dateOf": null
}

But Before this set your dateOf property as nullable in your entity class

public DateTime? Date { get; set; }

CodePudding user response:

You're trying to pass a string to an object of type DateTime. Try to implement a custom json converter.

In your C# property, add the declaration:

[JsonPropertyName("dateOf")]
[JsonConverter(typeof(stringToDateTimeConverter))]
public DateTime? date;

Here is an example:

public sealed class StringToDateTimeConverter : JsonConverter<double>
{
    public override double Read(
        ref Utf8JsonReader reader,
        Type typeToConvert, 
        JsonSerializerOptions options)
    {
        DateTime.TryParse(reader.GetString(),out DateTime value);
        return value;
    }

    public override void Write(
        Utf8JsonWriter writer,
        double value, 
        JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
}
  • Related