Home > database >  Serialize JSON from object to string / DateOnly
Serialize JSON from object to string / DateOnly

Time:02-08

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.

CodePudding user response:

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)})); 

Issue for DateOnly and TimeOnly support on github.

  •  Tags:  
  • Related