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

When deserializing a json string, it doesn't include the data

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;

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

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()); }

    }
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