繁体   English   中英

从ASP.NET Web API返回数字属性的可变长度json列表

[英]Returning variable length json list of numeric properties from ASP.NET Web API

ASP.NET MVC4 Web API控制器应返回json结果,其中包含数字属性名称和值,例如

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

属性名称以1开头。 属性和属性值的数量在代码中创建。 如何返回这样的结果?

我试过控制器

[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" }
       });
    }
 }

但是出现编译错误

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

列表中的元素数量也在运行时确定。 它没有像本示例中那样固定。 如何在代码中生成属性名称“ 1”,“ 2”及其值的可变长度列表。

如何从Web API返回这样的列表?

没错,您不能使用数字创建属性,但是可以肯定地用属性装饰属性,并具有一个包含所有属性的类( output )。 然后使用该class( output )发送响应。

完整的代码:

创建一个如下所示的类。

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; }
}

并使用以下命令发送数据。

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

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

编辑 -检查OP的注释后:- If we have n number of properties like (1,2,3..), then how输出class going to handle that?

解决方法 -然后直接使用字典

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"}
});

我认为Dictionary<string, string>完全按照您的需要序列化了。 因此,您可以创建类似以下的类:

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; }
}

当然,替代方法是直接手动创建json。

其他方式:

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;
}

在您的JS中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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