[RESOLVED]How to return variable length list with numeric property names from Web API

ASP.NET MVC4 Web API Controller should return json result which contains numeric propery names and values like

{ "openTimes":{"1":"09:00","2":"09:15","3":"09:30" }}

Propery names start with 1 . Number of properties and propery values are created in code.

How to return such result ?

I tried 

class output
    public string prop1 { get; set; }
    public string prop2 { get; set; }
    public string prop3 { get; set; }
public HttpResponseMessage Post()
    return Request.CreateResponse(HttpStatusCode.OK, new
        openTimes = new output() { prop1 = "09:00", prop2 = "09:15", prop3 = "09:30" }

but in this code number of elements in list is hard coded. How to return variable-length list ?


as your keys are not legal in .net, use the jsontextwriter.

prepare the dictionary<string,object> object and add all your properties as keys and values as values
convert dictionary to json and send to client


then at client, you can read json data in jquery like this

$.each( obj, function( key, value ) {

  alert( key + ": " + value );


Leave a Reply