Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize JSON from object to string / DateOnly

I have a JSON call from an object:

 public record SaveDate(DateOnly StartDate, string EndDate, Object[] objects);
var saveDate= new SaveDate(DateOnly.MinValue, DateTime.MaxValue.ToString("yyyy-MM-dd"), 
new Object[] { objects});

that when executes the API call it ends up returning

{
    "startDate": {
        "year": 1,
        "month": 1,
        "day": 1,
        "dayOfWeek": 1,
        "dayOfYear": 1,
        "dayNumber": 0
    },
    "endDate": "2022-07-07",
    "Object": [
        {
            "foo": "bar"
                }
            ]
        }
    ]
}

however I need to have the format sent from startDate to be the same as endDate ("yyyy-MM-dd") instead of the deserialized version. how can I do that?

note: I'm using DateOnly as type (.net 6.0) and the API expects a string in the format specified above.

like image 290
Baldie47 Avatar asked Dec 02 '25 06:12

Baldie47


1 Answers

DateOnly and TimeOnly binding is not fully supported yet. You can implement your own converter for this type:

public class DateOnlyJsonConverter : JsonConverter<DateOnly>
{
    private const string Format = "yyyy-MM-dd";

    public override DateOnly ReadJson(JsonReader reader,
        Type objectType,
        DateOnly existingValue,
        bool hasExistingValue,
        JsonSerializer serializer) =>
        DateOnly.ParseExact((string)reader.Value, Format, CultureInfo.InvariantCulture);

    public override void WriteJson(JsonWriter writer, DateOnly value, JsonSerializer serializer) => 
        writer.WriteValue(value.ToString(Format, CultureInfo.InvariantCulture));
}

class MyClass
{
    [JsonConverter(typeof(DateOnlyJsonConverter))]
    public DateOnly dt { get; set; }
}

// prints {"dt":"2021-01-01"}
Console.WriteLine(JsonConvert.SerializeObject(new MyClass{dt = new DateOnly(2021,1,1)})); 

For System.Text.Json - see this answer.

UPD

Recently released 13.0.2 version of Newtonsoft.Json supports DateOnly and TimeOnly:

13.0.2
New feature - Add support for DateOnly and TimeOnly

like image 64
Guru Stron Avatar answered Dec 03 '25 20:12

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!