1

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?

Roman Koliada
  • 4,286
  • 2
  • 30
  • 59
  • If you are only returning data from the API then you can use an anonymous object. If you need to also send it back change your Array property to dynamic and use a jObject to get the fields back out. – Stephen Brickner Nov 16 '15 at 12:21
  • 1
    But I don't need dynamic property, the type of array property won't change. Only it's json name in returned object should be changeable. And I don't want use anonymous objects because of flexibility, default values, documentation etc. – Roman Koliada Nov 16 '15 at 12:32

1 Answers1

1

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();
    }
}
Stephen Brickner
  • 2,584
  • 1
  • 11
  • 19
  • Thanks for help, but actually there are more than 2 responses and I don't want switch in every method. Ideally it should by smth like: Request.CreateResponse(HttpStatusCode.OK, new Response("test", 123, myArray, "someArray")); – Roman Koliada Nov 16 '15 at 12:37
  • 1
    Then you will need to implement your own contract resolver. Check out this post: http://stackoverflow.com/questions/26882986/overwrite-json-property-name-in-c-sharp – Stephen Brickner Nov 16 '15 at 12:39