In System.Text.Json how does the "setter" work when using properties that are of type List? it is not how i would expect, especially in relation to the setter for a string as example.
Here's what I mean:
public class Program
{
public static void Main()
{
var json = @"
{
""doot"": ""bloop bloop"",
""bars"":
[
{
""id"": 1
},
{
""id"": 2
}
]
}
";
var obj = JsonSerializer.Deserialize<Foo>(json);
Console.WriteLine($"obj.Doot: {obj.Doot}");
if (obj.Bars == null)
Console.WriteLine("Bars is null.");
else
Console.WriteLine($"obj.Bars.Count: {obj.Bars.Count}");
}
public class Foo
{
private string _doot;
[JsonPropertyName("doot")]
public string Doot
{
get => _doot;
set
{
Console.WriteLine($"Setting Doot to {value}");
_doot = value;
}
}
private List<Bar> _bars;
[JsonPropertyName("bars")]
public List<Bar> Bars
{
get => _bars;
set
{
Console.WriteLine($"Bars Value count during setter: {value.Count}");
_bars = value;
}
}
}
public class Bar
{
[JsonPropertyName("id")]
public int Id {get;set;}
}
}
output:
Setting Doot to bloop bloop
Bars Value count during setter: 0
obj.Doot: bloop bloop
obj.Bars.Count: 2
In the above, when the Doot setter fires, value has the value being set to the backing field _doot. When the Bars setter fires, value has something in it, but it is not the two Bar instances, as shown by the Console.WriteLine statement within the setter, which reports a 0 count.
If I needed to do some logic based on the values being set within the property Bars, how can I accomplish that if value does not have the information?
fiddle for reference:
https://dotnetfiddle.net/7z2O9S
EDIT:
it was pointed out to me elsewhere (caschw if you're here thanks) that the list is likely initialized as an empty list, then list.Add or list.AddRange could be used after initialization (i'm unclear which is used under the covers of System.Text.Json); meaning the setter would only ever be done once unless I change the reference to the list. This makes sense, but still, how would I hook into running some logic whenever the collection of Bars is changed?