Kuke Kuke - 1 month ago 18
ASP.NET (C#) Question

c# return json result as an array

Making demo version program
Trying to get Json object result as an array, 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
});
}
}
}
}

it returns:

{
"stampCode": "666",
"email": "666_doctor@gmail.com",
"phone": "+370 640 000000",
"healthCareProvider": "Jonavos poliklinika"
}


but i hope to get:

[
{
"stampCode": "666",
"email": "666_doctor@gmail.com",
"phone": "+370 640 000000",
"healthCareProvider": "Jonavos poliklinika"
}
]


if including array, then missing json object..and result gets:

[
"stampCode: 666",
"email: 666_doctor@gmail.com",
"phone: +370 640 000000",
"healthCareProvider: Jonavos poliklinika"
]


any opinions? iam new at programming and stuck on this

Answer

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...

Comments