Skip to content

Instantly share code, notes, and snippets.

@richlander
Created September 13, 2020 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richlander/bcb881c897f65c3fd804499846fcdefc to your computer and use it in GitHub Desktop.
Save richlander/bcb881c897f65c3fd804499846fcdefc to your computer and use it in GitHub Desktop.
`JsonSerializer` support for records
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
using System;
using System.Text.Json;
Forecast forecast = new(DateTime.Now, 40)
{
Summary = "Hot!"
};
string forecastJson = JsonSerializer.Serialize<Forecast>(forecast);
Console.WriteLine(forecastJson);
Forecast? forecastObj = JsonSerializer.Deserialize<Forecast>(forecastJson);
Console.Write(forecastObj);
public record Forecast (DateTime Date, int TemperatureC)
{
public string? Summary {get; init;}
};
@richlander
Copy link
Author

richlander commented Sep 13, 2020

Produces the following output:

rich@thundera jsonserializerrecords % dotnet run
{"Date":"2020-09-12T18:24:47.053821-07:00","TemperatureC":40,"Summary":"Hot!"}
Forecast { Date = 9/12/2020 6:24:47 PM, TemperatureC = 40, Summary = Hot! }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment