简体   繁体   English

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

[英]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 ASP.NET MVC4 Web API控制器应返回json结果,其中包含数字属性名称和值,例如

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

Propery names start with 1 . 属性名称以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. 如何在代码中生成属性名称“ 1”,“ 2”及其值的可变长度列表。

How to return such list from Web API ? 如何从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. 没错,您不能使用数字创建属性,但是可以肯定地用属性装饰属性,并具有一个包含所有属性的类( output )。 Then use that class( output ), to send response. 然后使用该class( output )发送响应。

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"}} 输出 - {"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? 编辑 -检查OP的注释后:- If we have n number of properties like (1,2,3..), then how输出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. 我认为Dictionary<string, string>完全按照您的需要序列化了。 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. 当然,替代方法是直接手动创建json。

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: 在您的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