Skip to content

Instantly share code, notes, and snippets.

@richlander

richlander/Program.cs Secret

Created Sep 11, 2020
Embed
What would you like to do?
`System.Text.Json` now supports Dictionaries with non-string keys
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>preview</LangVersion>
</PropertyGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Text.Json;
Dictionary<int, string> numbers = new ()
{
{0, "zero"},
{1, "one"},
{2, "two"},
{3, "three"},
{5, "five"},
{8, "eight"},
{13, "thirteen"},
{21, "twenty one"},
{34, "thirty four"},
{55, "fifty five"},
};
var json = JsonSerializer.Serialize<Dictionary<int, string>>(numbers);
Console.WriteLine(json);
var dictionary = JsonSerializer.Deserialize<Dictionary<int, string>>(json);
Console.WriteLine(dictionary[55]);
@richlander

This comment has been minimized.

Copy link
Owner Author

@richlander richlander commented Sep 11, 2020

Produces the following output.

rich@thundera jsondictionarykeys % dotnet run
{"0":"zero","1":"one","2":"two","3":"three","5":"five","8":"eight","13":"thirteen","21":"twenty one","34":"thirty four","55":"fifty five"}
fifty five
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment