When trying to deserialize a json string to an object of type Cart, the result is always empty even though the string contains data.
Code:
string str = this.HttpContext.Session.GetString("cart"); // {"Lines":[{"Id":9,"Count":1}]}
Cart c = JsonSerializer.Deserialize<Cart>(str);
c.Lines.Count() is 0;
Cart.cs:
[Serializable]
public sealed class Cart
{
private readonly ICollection<CartLine> _lines = new Collection<CartLine>();
public void Add(CartLine line)
{
_lines.Add(line);
}
public void Remove(int productId)
{
CartLine tmp = _lines.Single(cr => cr.Id == productId);
_lines.Remove(tmp);
}
public IEnumerable<CartLine> Lines => _lines;
}
CartLine.cs:
[Serializable]
public sealed class CartLine
{
public int Id { get; set; }
public int Count { get; set; }
}
>Solution :
property Lines doesn’t have a setter, should be
public IEnumerable<CartLine> Lines
{
get { return _lines; }
init { _lines = new Collection<CartLine>(value.ToList()); }
}