I'm trying to get my web service, written in .NET MVC5, to return JSON that I can consume in an iOS app. I thought I'd already succeeded, but looking more closely at the returned data - and bear in mind that this is all new to me, so forgive my terminology - it look as if I'm getting a JSON array rather than a JSON object.
This, I think, is causing issues when I follow online tutorials which show how to convert JSON objects into dictionaries in Swift for displaying in an app. As you can see from the output sample below, my JSON begins with [{"FirstName":"John"..., effectively launching straight into an array of People, when I think I want it to start something like {"People":[{"FirstName":"John"...
How can I get the JSON returned to be an object rather than just an array of people? I'm hoping I'm nearly there and perhaps just need to change a type somewhere?
Model:
public class PersonModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string DepartmentName { get; set; }
public IEnumerable<PhoneNumberModel> PhoneNumbers { get; set; }
}
Controller:
public class PersonController : ApiController
{
public IEnumerable<PersonModel> GetAllPersons()
{
List<PersonModel> person;
using (var context = new ContactsContext())
{
person = context.People.Include("PhoneNumbers.PhoneNumberType1").ToList()
.Select(p => new PersonModel
{
FirstName = p.FirstName,
LastName = p.LastName,
DepartmentName = p.Department1.Name,
PhoneNumbers = p.PhoneNumbers.Select(x => new PhoneNumberModel
{
PhoneNumberTypeName = x.PhoneNumberType1.Description,
TelephoneNumber = x.PhoneNumber1
})
}).ToList();
}
return person;
}
}
Output:
[{
"FirstName": "John",
"LastName": "Smith",
"DepartmentName": "Accounts",
"PhoneNumbers": [{
"PhoneNumberTypeName": "Office",
"TelephoneNumber": "12345"
}, {
"PhoneNumberTypeName": "Mobile",
"TelephoneNumber": "54321"
}]
}, {
"FirstName": "Jane",
"LastName": "Harris",
"DepartmentName": "HR",
"PhoneNumbers": [{
"PhoneNumberTypeName": "Mobile",
"TelephoneNumber": "98765"
}]
}]
IEnumerable<PersonModel>which is a collection, so it will always be converted to an Array in JSON.