Search code examples
c#jsonsystem.text.json

Json deserialization onto readonly fields in C#


I have a readonly struct. The struct, as it is readonly,must have readonly fields. However, I cannot apparently deserialize onto these fields from json. I would much like to keep my struct readonly though. How can I deserialize json to a readonly struct?

I am using the built-in json (System.Text.Json)


Solution

  • You could try to use JsonConstructor, as pointed out by @JonSkeet. However, if you want to have a struct without custom constructor, this is adressed in .Net 8, which releases this month, so if this is an option for you, I would recommend .Net 8.

    Here is the explaination: https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-8#read-only-properties