Skip to content

Instantly share code, notes, and snippets.

@SigurdJanson
Last active September 29, 2021 16:22
Show Gist options
  • Save SigurdJanson/4606c99b94c12b4d7cf78d91e38ec2df to your computer and use it in GitHub Desktop.
Save SigurdJanson/4606c99b94c12b4d7cf78d91e38ec2df to your computer and use it in GitHub Desktop.
De-serialise IReadOnlyList property in C# that cannot be set outside the class.
/*
How to de-serialise a property that returns an IReadOnlyList and shall not be set
from outside?
*/
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
public class PersonClass
{
public string Name { get; set;}
public int Age { get; set;}
protected List<string> children;
public IReadOnlyList<string> Children
{
get { return children.AsReadOnly(); }
protected set { children = new List<string>(value); }
}
public PersonClass()
{
children = new();
}
[JsonConstructor]
public PersonClass(IReadOnlyList<string> children) : base()
{
this.Children = children;
}
public override string ToString()
{
string ChildrenString = "";
foreach(var c in Children)
ChildrenString += c;
return $"Name: {Name}, Age: {Age}, Children: {Children.Count} ({ChildrenString})";
}
}
public class Program
{
public static void Main()
{
var json = @"{""Age"":23, ""Name"":""Taro"", ""Children"": [""Ich"", ""Du""]}";
var person = JsonSerializer.Deserialize<PersonClass>(json);
Console.WriteLine(person.ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment