Home > Net >  Returning the full object in response body using NET Core controller
Returning the full object in response body using NET Core controller

Time:02-10

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?

CodePudding user response:

The enter image description here

  •  Tags:  
  • Related