Last active
September 29, 2021 16:22
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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