Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading