[英]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.