Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,38 @@
WriteIndented = true
});
Console.WriteLine(systemJsonComplex);
Console.WriteLine();

// Using System.Text.Json with a converter for the key type only
Console.WriteLine("============ Complex Dictionary: System.Text.Json w/ Key Converter ============");
var systemJsonKeyConverter = JsonSerializer.Serialize(invoicesByCustomer, new JsonSerializerOptions
{
Converters = { new CustomerKeyConverter() },
WriteIndented = true
});
Console.WriteLine(systemJsonKeyConverter);
Console.WriteLine();

// Using System.Text.Json after projecting the keys to Guid
Console.WriteLine("============ Complex Dictionary: System.Text.Json w/ Guid Keys ============");
var invoicesByCustomerId = invoicesByCustomer.ToDictionary(pair => pair.Key.CustomerId, pair => pair.Value);
var systemJsonGuidKeys = JsonSerializer.Serialize(invoicesByCustomerId, new JsonSerializerOptions
{
WriteIndented = true
});
Console.WriteLine(systemJsonGuidKeys);
Console.WriteLine();

// Using System.Text.Json with a naming policy for the keys
Console.WriteLine("============ System.Text.Json - camelCase Keys ============");
var stockByProduct = new Dictionary<string, int>
{
{"AppleCount", 3},
{"OrangeCount", 5}
};
var systemJsonCamelCaseKeys = JsonSerializer.Serialize(stockByProduct, new JsonSerializerOptions
{
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
});
Console.WriteLine(systemJsonCamelCaseKeys);
Console.WriteLine();
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.Text.Json;
using System.Text.Json.Serialization;

namespace JsonSerializeToDictionaryDataModel;

public sealed class CustomerKeyConverter : JsonConverter<Customer>
{
public override Customer Read(ref Utf8JsonReader reader, Type typeToConvert,
JsonSerializerOptions options)
{
// Since we are only dealing with Serializing in this article, we don't need to implement the Read method
throw new NotImplementedException();
}

public override void Write(Utf8JsonWriter writer, Customer value, JsonSerializerOptions options)
=> writer.WriteStringValue($"Customer-{value.CustomerId:N}");

public override void WriteAsPropertyName(Utf8JsonWriter writer, Customer value,
JsonSerializerOptions options)
=> writer.WritePropertyName($"Customer-{value.CustomerId:N}");
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System.Text.Json;

namespace JsonSerializeToDictionaryDataModel.Tests;

public class CustomerKeyConverterUnitTest
{
private static readonly Customer Customer = new(
"123 Nowhere Street, Fakeville, MD",
"555-555-0001",
new Person("John", "Smith"),
Guid.Parse("bfafbb48-f670-4e0e-87f6-d44ac219cf7b"));

[Fact]
public void GivenDictionaryWithCustomerKeys_WhenSerializedWithoutConverter_ThenThrowsNotSupportedException()
{
var dictionary = new Dictionary<Customer, int> { { Customer, 2 } };

Assert.Throws<NotSupportedException>(() => JsonSerializer.Serialize(dictionary));
}

[Fact]
public void GivenDictionaryWithCustomerKeys_WhenSerializedWithKeyConverter_ThenKeyIsCustomerId()
{
var dictionary = new Dictionary<Customer, int> { { Customer, 2 } };
var options = new JsonSerializerOptions { Converters = { new CustomerKeyConverter() } };

var result = JsonSerializer.Serialize(dictionary, options);

Assert.Equal("{\"Customer-bfafbb48f6704e0e87f6d44ac219cf7b\":2}", result);
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

Expand All @@ -10,15 +10,15 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Bogus" Version="34.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageReference Include="NJsonSchema" Version="10.8.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PackageReference Include="Bogus" Version="35.6.5" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageReference Include="NJsonSchema" Version="11.6.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.2.0">
<PackageReference Include="coverlet.collector" Version="10.1.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
Expand Down
Loading