Brian Reading
Brian Reading

Reputation: 598

How do I return a list as a JSON object with a nested array instead of just an array?

Using ASP.NET Core web API framework, my controller returns a list, which currently formats its output in JSON as a plain array. How do I wrap an object around this so it outputs as an object with an array nested inside of it instead?

I know that I can do this by creating a new class to hold this list as a property, but I wanted to know if there is a cleaner way that I can do this code block (especially since the class would only be used for this method).

My controller code is as follows:

public async Task<IActionResult> GetIntranets(string utilityServer,
     string configuration) {

     List<Intranet> intranets = 
          await _intranetService.GetIntranets(utilityServer, configuration);
            
     return new OkObjectResult(intranets);
}

Current output:

[
  {
    "name": "Intranet 1",
    "taskmanPath": "\\\\hostname\\syteline",
    "reportPreviewUrl": "https://cname.domain.com/slreports",
    "reportServerUrl": "http://hostname/ReportServer_XYZ_TEST",
    "masterSite": "DALS"
  },
  {
    "name": "Intranet 2",
    "taskmanPath": "\\\\hostname\\syteline",
    "reportPreviewUrl": "https://cname.domain.com/slreports",
    "reportServerUrl": "http://fqdn/ReportServer_XYZ_PILOT",
    "masterSite": "DALS"
  },
]

Desired output:

{
  "Intranets": [
    {
      "name": "Intranet 1",
      "taskmanPath": "\\\\hostname\\syteline",
      "reportPreviewUrl": "https://cname.domain.com/slreports",
      "reportServerUrl": "http://hostname/ReportServer_XYZ_TEST",
      "masterSite": "DALS"
    },
    {
      "name": "Intranet 2",
      "taskmanPath": "\\\\hostname\\syteline",
      "reportPreviewUrl": "https://cname.domain.com/slreports",
      "reportServerUrl": "http://fqdn/ReportServer_XYZ_PILOT",
      "masterSite": "DALS"
    }
  ]
}

Upvotes: 1

Views: 2765

Answers (1)

Michael
Michael

Reputation: 86

If you change your code to look like this:

public async Task<IActionResult> GetIntranets(string utilityServer, string configuration)
{
     List<Intranet> intranets = 
          await _intranetService.GetIntranets(utilityServer, configuration);
     
     var objectWrapper = new 
     {
        Intranets = intranets
     };     
     return new OkObjectResult(objectWrapper);
}

An anonymous object will be created and serialized how you want it to be. There was an answer regarding the fact that anonymous types shouldn't be used because of type safety, but by returning an OkObjectResult you are dealing with type of object anyway, which already disregards type safety.

This wasn't mentioned in your question, but in case you are wondering how to deserialize it, you can take a look at this good example: https://www.newtonsoft.com/json/help/html/DeserializeAnonymousType.htm

Upvotes: 4

Related Questions