简体   繁体   中英

Returning variable length json list of numeric properties from ASP.NET 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 controller

[HttpPost]
public class TestController : ApiController
 {
    public HttpResponseMessage Post()
    {
   return Request.CreateResponse(HttpStatusCode.OK, new {
      openTimes = new { @"1"="09:00", @"2"="09:15", @"3"="09:30" }
       });
    }
 }

but got compile error

Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

Also number of elements in list is determined at runtime. It is not fixed as in this sample. How to generate variable length list of property names "1", "2" and their values in code.

How to return such list from Web API ?

You are right, you can not create property with numeric, but you can definitely decorate with attribute for property and have a class ( output ) to contain all properties. Then use that class( output ), to send response.

Complete code:

Create a class like following.

class output
{
    [Newtonsoft.Json.JsonProperty("1")]
    public string prop1 { get; set; }
    [Newtonsoft.Json.JsonProperty("2")]
    public string prop2 { get; set; }
    [Newtonsoft.Json.JsonProperty("3")]
    public string prop3 { get; set; }
}

And use following to send data.

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

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

EDIT - After checking OP's comment:- If we have n number of properties like (1,2,3..), then how output class going to handle that?

Solution - Then directly use dictionary

Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "09:00");
dic.Add(2, "09:15");
dic.Add(3, "09:30");
return Request.CreateResponse(HttpStatusCode.OK, new
{
    openTimes = dic
    //openTimes = new output() { prop1 = "09:00", prop2 = "09:15"}
});

I think that a Dictionary<string, string> is serialized exactly as you want. So you can probably create a class like:

public class TestController : ApiController
{
    public YourOutput Get()
    {
        var openTimes = new Dictionary<string, string>
        {
            {"1", "0:09"},
            {"2", "2:09"},
            {"3", "1:09"},
        };

        return new YourOutput() { openTimes = openTimes };
    }
}

public class YourOutput
{
    public Dictionary<string, string> openTimes { get; set; }
}

An alternative of course is to directly create your json manually.

Another way:

public HttpResponseMessage Post()
{
         HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
         response.Content =
             new StringContent("{\"openTimes\":{\"1\":\"09:00\", \"2\":\"09:15\", \"3\":\"09:30\"}}");
         return response;
}

In your JS:

var result = JSON.parse(data);
if (result.openTimes[1] == "09:00"){
   // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM