Skip to content

Instantly share code, notes, and snippets.

@richlander
Created September 11, 2020 18:35
Show Gist options
  • Save richlander/622028863a10bd2051a5ba47b903d839 to your computer and use it in GitHub Desktop.
Save richlander/622028863a10bd2051a5ba47b903d839 to your computer and use it in GitHub Desktop.
`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
Copy link
Author

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