Kuke
Kuke

Reputation: 37

c# return json result as an array

I am making a WebApi application, and trying to get my controller to return a Json object result that is within an array.

I want my response to be formatted like this:

[
  {
    "stampCode": "666",
    "email": "[email protected]",
    "phone": "+370 640 000000",
    "healthCareProvider": "Jonavos poliklinika"
  }
]

But my code in its current state is returning the following instead:

{
  "stampCode": "666",
  "email": "[email protected]",
  "phone": "+370 640 000000",
  "healthCareProvider": "Jonavos poliklinika"
}

When I tried including an array myself, my output loses the JSON object and therefore looks as such:

[
  "stampCode: 666",
  "email: [email protected]",
  "phone: +370 640 000000",
  "healthCareProvider: Jonavos poliklinika"
]

How can I fix my code to get the desired output? I'am new to programming and really stuck on this.

Here's my code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Web.Http;
using System.Web.Http.Results;

namespace DoctorWebService.Controllers
{
    public class DataController : ApiController
    {
        [Authorize]
        [HttpGet]
        [Route("api/doctors")]
        public JsonResult<object> Get(string doctorCode)
        {
            if (doctorCode == "666")
            {
                var identity = (ClaimsIdentity)User.Identity;
                return Json<object>(new 
                {
                    stampCode = "666",
                    email = "[email protected]",
                    phone = "+370 640 000000",
                    healthCareProvider = "Jonavos poliklinika"
                });
            }
            else
            {
                return Json<object>(new
                {
                    notFound = 0
                });
            }
        }
    }
}

Upvotes: 2

Views: 17847

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499800

Well yes, you're just creating a new anonymous type. It's easy to wrap that in an array though:

return Json(new[] { new
{
    stampCode = "666",
    email = "[email protected]",
    phone = "+370 640 000000",
    healthCareProvider = "Jonavos poliklinika"
}});

It's not clear why you'd want to return an array though, when you're trying to find a single doctor. If I were an API consumer, I'd find that pretty confusing, I think...

Upvotes: 6

Tinwor
Tinwor

Reputation: 7973

You are creating a JSON Object and not a JSON Array so the result that you are getting is correct.
if you want return a JSON Array you need to return something like this:

new[]{
  //obj1, obj2,obj3
}

And the result will be a JSON Array of your objects

Upvotes: 0

Related Questions