将动态变量转换为 List<model>或数组 [英] Converting a dynamic Variable to List<model> or array
问题描述
我想将这个带有 Ajax 的数组发送到 api :
I want to send this Array with Ajax to api :
var receipt = Array();
receipt = [
{ 'Service': 'Saab', 'Order': '20' },
{ 'Service': 'Volvo', 'Order': '12' },
{ 'Service': 'BMW', 'Order': '25' }
];
这是我的 Ajax 主体:
And this is my Ajax body :
var r = JSON.stringify(receipt);
$.ajax({
type: "POST",
dataType: "Json",
contentType: "application/json; charset=utf-8",
data: r,
url: "api/Receipt",
success: function (result) {
// To Do
console.info(result);
},
error: function (result) {
console.info(result);
}
});
这就是我作为 Json 得到的:
And this is what i get as Json :
{[
{
"Service": "Saab",
"Order": "20"
},
{
"Service": "Volvo",
"Order": "12"
},
{
"Service": "BMW",
"Order": "25"
}
]}
我在 api 端捕捉它们就像这样:
And i catch them in api side Like this :
[Route("api/Receipt")]
[WebMethod]
public string Receipt_Turn(object obj)
{
dynamic dyn = JsonConvert.DeserializeObject(obj.ToString());
if (dyn != null)
{
return dyn[1].ToString();
}
else
{
return "false";
}
}
它可以工作,return dyn[1].ToString()
部分返回我的数组的第二条记录.但我想将此动态变量转换为模型的列表或数组.
And it works, the part return dyn[1].ToString()
returns second record of my Array. But i want to convert this dynamic variable to a list or array of a model .
这是我的模型:
[Serializable()]
public class Receipt
{
public string Service { get; set; }
public string Order { get; set; }
}
我想这样做:
string serv = receipt[1].Service;
我该怎么做?
谢谢...
推荐答案
删除 JS 脚本中的数组部分并像这样编写:
Delete the Array Part in Your JS Script and Write it Like this :
var receipt = [
{ 'Service': 'Saab', 'Order': '20' },
{ 'Service': 'Volvo', 'Order': '12' },
{ 'Service': 'BMW', 'Order': '25' }
];
在这种形状中,您正在发送一个对象.在你的代码中,我猜你正在发送一个 JArray
所以它会在从 JArray
转换为另一种类型时产生一些问题.
in this shape you are sending an Object. in your code i guess you are sending an JArray
So it Will make some Problems in Converting from JArray
to another Type .
在您的 API 端,编辑您的代码如下:
in your API Side , Edit Your Code As Below :
public string Receipt_Turn(object r)
{
//important Line Here
List<Receipt> rr = JsonConvert.DeserializeObject<List<Receipt>>(r.ToString());
if (rr != null)
{
return rr[1].ToString();
}
else
{
return "false";
}
}
如您所见,我们像对象一样获取它,然后我们将能够像我提到的那样准备您的 DeserializeObject
部分.
as you can see, we get it Like an Object and then we will be able to Get Ready your DeserializeObject
part Like i mentioned.
你最需要声明你的模型列表,然后在 DeserializeObject
部分之后添加你想要将它转换为的类型.
you most declare a List of your Model, and after part DeserializeObject
add that Type You want to Convert it to.
这里因为我们声明了 List
,我们应该将我们的 DeserializeObject
转换成它,所以我们添加 >
DeserializeObject
之后的代码>.
here Cause we Declared List<Receipt>
, we should convert our DeserializeObject
to it, so we add <List<Receipt>>
after DeserializeObject
.
最后你可以随心所欲地使用它.
and Finally you can use it Like You wish .
string serv = rr[1].Service;
这篇关于将动态变量转换为 List<model>或数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!