Reputation: 5122
I' m developing some WebAPI and have to return HttpResponseMessage with 2 standart service fields and one field which contains an array. Something like this:
{
field1:"test",
field2:123,
array:[{},{}]
}
But actually i need several responses which should differ only in name of array property:
{
field1:"test",
field2:123,
someArray:[{},{}]
}
and
{
field1:"test",
field2:123,
someOtherArray:[{},{}]
}
Type of elemnts in array is the same in each response. So I want to create one class for such type of responses and just change its PropertyName. Like this one:
public class Response
{
public int field2 { get; set; }
public string field1 { get; set; }
[JsonProperty(PropertyName = ???)]
public IEnumerable<SomeType> Array { get; set; }
}
How can I implement it?
Upvotes: 1
Views: 1670
Reputation: 2602
You could also consider using a dictionary.
[HttpGet, Route("api/yourroute")]
public IHttpActionResult GetSomeData()
{
try
{
var data = new Dictionary<string, dynamic>();
data.Add("field1", "test");
data.Add("field2", 123);
var fieldName = someCondition == true? "someArray" : "someOtherArray";
data.Add(fieldName, yourArray);
return Ok(data);
}
catch
{
return InternalServerError();
}
}
Upvotes: 1