Serialize Inherited objects

  • Thread starter Thread starter edsondiasalves
  • Start date Start date
E

edsondiasalves

Guest
Hello

I am using a Web Api with .Net core 3.1 and when I try to return a structure like this:

[
{
"Id": 1,
"Author": "Stephen King"
},
{
"Id": 2,
"RamMemoryAmount": 4
}
]


It returns this:

[
{
"Id": 1
},
{
"Id": 2
}
]


I am using OOP to optmize it

using System;
using System.Collections.Generic;
using System.Text.Json;

public class Program
{
public static void Main()
{
List<IProduct> products = new List<IProduct>();

products.Add(new Book(){ Id = 1, Author = "Stephen King" });
products.Add(new Computer(){ Id = 2, RamMemoryAmount = 4 });

string json = JsonSerializer.Serialize(products);
Console.WriteLine(json);
}
}

interface IProduct {
int Id { get; set; }
}

class Product: IProduct {
public int Id { get; set; }
}

class Book : Product{
public string Author { get ;set; }
}

class Computer : Product {
public int RamMemoryAmount { get; set; }
}

Any thoughts?

You can try it here: C# Online Compiler | .NET Fiddle

Continue reading...
 
Back
Top