-
-
Save richlander/bcb881c897f65c3fd804499846fcdefc to your computer and use it in GitHub Desktop.
`JsonSerializer` support for records
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Project Sdk="Microsoft.NET.Sdk"> | |
<PropertyGroup> | |
<OutputType>Exe</OutputType> | |
<TargetFramework>net5.0</TargetFramework> | |
<LangVersion>preview</LangVersion> | |
<Nullable>enable</Nullable> | |
</PropertyGroup> | |
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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;} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Produces the following output: