C# 10 - implementing Record Structs and Deserialization of Nested Immutable Collections
I'm converting an old project and I'm trying to deserialize a JSON string into a record struct that contains an immutable collection, but I'm working with issues with the deserialization process... Specifically, I'm using System.Text.Json for the deserialization, and I have a record struct defined as follows: ```csharp using System.Collections.Immutable; public record struct Person(string Name, ImmutableArray<Address> Addresses); public record struct Address(string Street, string City); ``` The JSON I'm trying to deserialize looks like this: ```json { "Name": "John Doe", "Addresses": [ { "Street": "123 Main St", "City": "Anytown" }, { "Street": "456 Elm St", "City": "Othertown" } ] } ``` However, when I attempt to deserialize using the following code: ```csharp string json = /* JSON string here */; var person = JsonSerializer.Deserialize<Person>(json); ``` I get the following exception: ``` System.Text.Json.JsonException: The JSON value could not be converted to System.Collections.Immutable.ImmutableArray`1[Address]. ``` I've looked into the documentation and tried to use a custom converter for `ImmutableArray`, but I need to seem to get that working correctly. Hereβs my attempt at a custom converter: ```csharp public class ImmutableArrayJsonConverter<T> : JsonConverter<ImmutableArray<T>> { public override ImmutableArray<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var list = new List<T>(); while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) { var item = JsonSerializer.Deserialize<T>(ref reader, options); list.Add(item); } return list.ToImmutableArray(); } public override void Write(Utf8JsonWriter writer, ImmutableArray<T> value, JsonSerializerOptions options) { writer.WriteStartArray(); foreach (var item in value) { JsonSerializer.Serialize(writer, item, options); } writer.WriteEndArray(); } } ``` I registered the converter in my `JsonSerializerOptions`: ```csharp var options = new JsonSerializerOptions(); options.Converters.Add(new ImmutableArrayJsonConverter<Address>()); var person = JsonSerializer.Deserialize<Person>(json, options); ``` Unfortunately, I'm still working with the same deserialization behavior. What am I missing? Is there a better way to handle deserialization of record structs with immutable collections in C# 10? Any suggestions or best practices would be greatly appreciated! For context: I'm using Csharp on Windows 10. I'd love to hear your thoughts on this. Cheers for any assistance!