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": "666_doctor@gmail.com",
"phone": "+370 640 000000",
"healthCareProvider": "Jonavos poliklinika"
}
]
But my code in its current state is returning the following instead:
{
"stampCode": "666",
"email": "666_doctor@gmail.com",
"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: 666_doctor@gmail.com",
"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 = "666_doctor@gmail.com",
phone = "+370 640 000000",
healthCareProvider = "Jonavos poliklinika"
});
}
else
{
return Json<object>(new
{
notFound = 0
});
}
}
}
}
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 = "666_doctor@gmail.com",
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...
See more on this question at Stackoverflow