karenpayneoregon / newtonsoft-code

Shows how to use DateOnly and TimeOnly with JSON.NET

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JSON.NET and DateOnly/TimeOnly support

Code samples for Json.net which as of version 13.0.2 now supports DateOnly and TimeOnly. Three code samples are used to show interactions with Bogus and Microsoft.Data.SqlClient which is most likely used to work with json data.

Sample Description
Sample1 Created a list of mocked people, serialize then deserialize with Json.net
Sample2 Same as Sample1 but uses Bogus NuGet package to create a list. Bogus just began support for DateOnly and TimeOnly with Json.net
DataOperations.Read Reads DateOnly and TimeOnly from a SQL-Server database using a preview2 version of Microsoft.Data.SqlClient to seriale to json with Json.net

Requires


json

[
  {
    "Id": 1,
    "FirstName": "Karen",
    "LastName": "Payne",
    "StartDate": "2022-12-01",
    "StartTime": "14:15:00"
  },
  {
    "Id": 2,
    "FirstName": "May",
    "LastName": "Gallagher",
    "StartDate": "2022-12-11",
    "StartTime": "16:00:00"
  }
]

Model

public class Container
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateOnly StartDate { get; set; }
    public TimeOnly StartTime { get; set; }
}

Mocked data

public class Mocked
{
    public  static List<Container> Container() =>
        new()
        {
            new()
            {
                Id = 1, 
                FirstName = "Karen", 
                LastName = "Payne", 
                StartDate = new DateOnly(2022,12,1), 
                StartTime = new TimeOnly(14,15)
            },
            new()
            {
                Id = 2, 
                FirstName = "May", 
                LastName = "Gallagher", 
                StartDate = new DateOnly(2022,12,11), 
                StartTime = new TimeOnly(16,0)
            }
        };
}

Get mocked data

var containers = Mocked.Container();

Serialize data

string json = JsonConvert.SerializeObject(containers, Formatting.Indented);

Deserialize data

var readContainers = JsonConvert.DeserializeObject<List<Container>>(json);

Screenshot1

About

Shows how to use DateOnly and TimeOnly with JSON.NET


Languages

Language:C# 100.0%