'Returning the full object in response body using NET Core controller

What is the best way to return all details of complex objects in the body of a HTTP response?

I made some simple test classes:

public class Parent { }

public class Child : Parent
{
    public Child(string _name) { name = _name; }
    public string name { get; }
}

I want to return a list as a response, which contains full detail about all the objects in it. My controller looks like this:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpGet]
    public List<Parent> Index()
    {
        Parent o1 = new Child("Alice");
        Parent o2 = new Child("Bob");
        return new List<Parent>() { o1, o2 };
    }
}

This leads to an output of [{},{}]

If I replace the definitions to work with the List<Child> return type, it is able to recognise the details as [{"name":"Alice"},{"name":"Bob"}], however I may have different child types in the list, so this would not work.

What function does NET Core use to convert the object into the JSON response body? Is the best way to tackle this problem to convert it to JSON myself and output the resulting string?



Solution 1:[1]

The ControllerBase.Ok method will return JSON formatted data by default, so you can just call:

return Ok(new List<Parent>() { o1, o2 });

Solution 2:[2]

You can try to use Object:

[HttpGet]
    public List<Object> Index()
    {
        Object o1 = new Child("Alice");
        Object o2 = new Child("Bob");
        return new List<Object>() { o1, o2 };
    }

result:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gUnleash
Solution 2 Yiyi You