Wrote a simple function for Web API 2 which returns the list of countries. It returns the valid Json format but without the array/object name. I have a bit of difficulty understand how this is achieved?
Here is my C# code:
[Route("Constants/CountryList")]
[HttpGet]
public IHttpActionResult GetCountryList()
{
IEnumerable<ISimpleListEntity> list = new CountryStore().SimpleSortedListByName();
if (list == null || !list.Any())
{
return NotFound();
}
return Ok(list);
}
ISimpleListEntity interface code is here.
public interface ISimpleListEntity
{
int Id { get; set; }
string Name { get; set; }
}
This service returns the following Json output (without the object/array name):
[
{
"Id":1,
"Name":"[Select]"
},
{
"Id":4,
"Name":"India"
},
{
"Id":3,
"Name":"Singapore"
},
{
"Id":2,
"Name":"United Arab Emirates"
}
]
But, am struggling to achieve the following Json format (WITH the object/array name called 'CountryList'):
{
"CountryList":[
{
"Id":1,
"Name":"[Select]"
},
{
"Id":4,
"Name":"India"
},
{
"Id":3,
"Name":"Singapore"
},
{
"Id":2,
"Name":"United Arab Emirates"
}
]
}
You could either create a specific class for this, as per the answer from Boas, or just use an anonymous type:
return Ok(new { CountryList = list });
Basically, you need an object with the appropriate property, one way or the other. If you want to deserialize this later and keep compile-time checking, it would be worth creating a class - but if you're either using dynamic typing or the consumer won't be the C# code anyway, then an anonymous type would be simpler.
See more on this question at Stackoverflow