Szymon D
Szymon D

Reputation: 441

How to return an array of objects with different schema in ASP.NET Core Web API?

Let's say I have ClassA and ClassB, both derive from MainClass. I would like to return a list of instances of those classes. I tried to return List<MainClass>, but default JSON serializer doesn't include properties from ClassA and ClassB.

Upvotes: 0

Views: 2385

Answers (1)

Madison Haynie
Madison Haynie

Reputation: 488

This worked fine for me

using System;
using System.Collections.Generic;
using Newtonsoft.Json;


public class Program
{
    public static void Main()
    {
        var list = new List<MainClass>{new A{PropA = "a", MainProp = "mainA"}, new B{PropB = "b", MainProp = "mainB"}};
        string output = JsonConvert.SerializeObject(list);

        Console.WriteLine(output);

    }


    public class MainClass {
        public string MainProp { get; set; }    
    }

    public class A : MainClass {

        public string PropA { get; set; }
    }

    public class B : MainClass {

        public string PropB { get; set; }
    }
}

Output:

[{"PropA":"a","MainProp":"mainA"},{"PropB":"b","MainProp":"mainB"}]

Upvotes: 2

Related Questions