0

So I currently have the following code

if (File.Exists(file))
{
    IList<Cart> temp = JsonConvert
        .DeserializeObject<IList<Cart>>(File.ReadAllText(file));
    foreach (var x in temp)
    {
        crt.Add(x);
    }
}

With class Cart being the base class and Drinks and Food being its derivation classes with its own different variables. When I use the above code to store the results of deserialization into crt, which is an list of cart with both Drinks and Food objects, the results when I try to display each item inside the cart becomes Cart_Project.Model.Cart rather than showing the variables of its derived classes. I've tried to use

foreach(var x in temp)
{
    if (x is Food)
    {
        crt.Add(x as Food);
    }
    else if (x is Drinks)
    {
        crt.Add(x as Drinks);
    }
}

To add each object as its own derived class, but nothing shows up when I try to display it on my app. Is theres any way to read each object from the file and store it into a List of its own class?

Magnetron
  • 7,495
  • 1
  • 25
  • 41
1234 5678
  • 23
  • 4
  • Does this answer your question? [Json.net serialize/deserialize derived types?](https://stackoverflow.com/questions/8513042/json-net-serialize-deserialize-derived-types) – Roar S. Jul 06 '21 at 17:28

1 Answers1

0

If you make the collection of type parent class (Cart in your example), then you are agreeing that those objects are of type Cart, thus losing the child class specifics. You will have to decide what design is best, but one potential option to consider is doing something related to having both classes implement an interface and make a collection of that interface.

public interface IConsumables { … }

public class Drinks: IConsumables 
{
    public string Name;
    public double Volume;
    public double Cost;
    public double Origin;
    public double Calories;
}

public class Food : IConsumables 
{
    public string Name;
    public double Cost;
    public double Origin;
    public double Calories;
}

Then use a some collection of that interface

IEnumerable<IConsumables>
Goku
  • 1,565
  • 1
  • 29
  • 62