[英]How to iterate over object sent via AJAX JSON
I have the following JavaScript object: 我有以下JavaScript对象:
var parameters = { "parameters" :
[
{
"key": "feedbackSource",
"value": "foo"
}, {
"key": "status",
"value": "foo"
}, {
"key": "feedbackType",
"value": "foo"
}
]
};
console.log(JSON.stringify(parameters)) shows: console.log(JSON.stringify(parameters))显示:
{"parameters":[{"key":"feedbackSource","value":"foo"},{"key":"status","value":"foo"},{"key":"feedbackType","value":"foo"}]}
AJAX: AJAX:
$.ajax({
type: "POST",
url: "myPage.aspx/MyMethod",
data: JSON.stringify(parameters),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Method: 方法:
[WebMethod]
public static void MyMethod(object parameters)
{
}
I have tried: 我努力了:
foreach (var p in (IEnumerable) parameters)
{
foreach (var x in (IEnumerable) p)
{
var test = x;
}
}
But test
on the first iteration is a Key Value pair, with Key = "key"
and Value = "feedbackSource"
. 但是第一次迭代的test
是一个Key Value对,其中Key = "key"
和Value = "feedbackSource"
。 On the second iteration, Key = "value"
and Value = "foo"
在第二次迭代中, Key = "value"
和Value = "foo"
And that doesn't seem like the correct way to iterate over the object. 这似乎不是迭代对象的正确方法。 I would expect the Key = "feedbackSource"
and Value = "foo"
. 我期望Key = "feedbackSource"
和Value = "foo"
。
var parameters =
{
"parameters":
[
{"feedbackSource": "foo", "status": "foo", "feedbackType": "foo"}
]
};
create below class 创建下课
public class mComputedProp
{
public string feedbackSource { get; set; }
public string status { get; set; }
public string feedbackType { get; set; }
}
public class mcomputedprops
{
[JsonProperty("parameters")]
public List<mComputedProp> mprops = new List<mComputedProp>();
}
Modify your ajax call 修改你的ajax调用
$.ajax({
type: "POST",
url: '@Url.Action("getComputedProperty", "Home")',
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
data: JSON.stringify({ listjson: JSON.stringify(parameters) })
});
[WebMethod]
public void getComputedProperty(string listjson)
{
mcomputedprops mod = JsonConvert.DeserializeObject<mcomputedprops>(listjson);
string asdf = mod.mprops[0].feedbackSource.ToString();
}
"How do I iterate over that object in C# to get the contents" “如何在C#中迭代该对象以获取内容”
After a good discussion with @Devlin about this - the following conclusion has been reached: 与@Devlin进行了很好的讨论之后-已得出以下结论:
The JSON string that is being generated (from the page) is a little confusing to say the least. 至少可以说,从页面生成的JSON字符串有点令人困惑。
The existing data structure of 现有的数据结构
{ "parameters" : [ { "key": "feedbackSource", "value": "foo" }, { "key": "status", "value": "foo" }, { "key": "feedbackType", "value": "foo" } ] };
Was very confusing and obfuscated the data somewhat - making it very hard to traverse and iterate the objects inside. 数据非常混乱并且有些混乱-使得遍历和迭代内部对象非常困难。
It appeared to be of key:(key/value) pairs/pairs ( wait, what? ) 它似乎是关键的:(key / value)对/对( 等等,什么? )
I proposed to structure a proper key/value pair structure to the JSON firstly (from within the page). 我建议首先(从页面内部)为JSON构建适当的键/值对结构。
Like so: 像这样:
{ "parameters" :
[
{
"feedbackSource" : "foo"
},
{
"status" : "foo"
},
{
"feedbackType" : "foo"
}
]
}
As per @Devlin's screenshot: 根据@Devlin的屏幕截图:
The ModelBinder was cleverly assiging parameter
as a Dictionary<string, object>
, because it recognised the JSON as key/value pairs - in which the values were yet again key value pairs . ModelBinder 巧妙地将 parameter
辅助为Dictionary<string, object>
,因为它将JSON识别为键/值对-其中的值又是键值对 。
Obviously, every type in C# derives from object
, so accepting this was just boxing it in an object
. 显然,C#中的每个类型都源自object
,因此接受它只是将其装在object
。
Thus why other suggestions of casting to a string
weren't successful. 因此,为什么其他转换为string
建议都没有成功。
ASP.NET has a ModelBinder which is able to detect types of objects passed to methods, to make it easier when getting data out in the method. ASP.NET具有ModelBinder,它能够检测传递给方法的对象的类型,从而使在方法中获取数据时更加容易。
Cast the object parameter
in the MyMethod
signature to a Dictionary<string, string>
(do it safely, where possible) 将MyMethod
签名中的object parameter
强制转换为Dictionary<string, string>
(在可能的情况下,请安全地进行操作)
Like so: 像这样:
var paramsDict = parameters as Dictionary<string, object>;
if (paramsDict != null)
{
// Iterate over the dictionary in here
}
Seeing as we know that the object parameters
is already of type Dictionary<string, object>
(thanks to some wizardry by the ModelBinder), we could just use this type in the MyMethod
signature, instead. 就像我们知道object parameters
已经是Dictionary<string, object>
(由于使用ModelBinder进行了一些向导),我们可以在MyMethod
签名中使用这种类型。
Like this: 像这样:
[WebMethod]
public static void MyMethod(Dictionary<string, object> parameters)
{
// Iterate in here
}
Now that you've got a nice and easy to use Dictionary<string, object>
, it is simple to iterate over it and grab the values from there. 现在,您已经有了一个好用且易于使用的Dictionary<string, object>
,可以轻松地对其进行迭代并从那里获取值。
Like this: 像这样:
foreach (var param in paramsDict) // or "... in parameters" if you're using suggestion 2
{
var key = param.Key;
var value = param.Value;
// Manipulate/persist the data
}
It's up to you how you then manipulate/persist the data, but this should give you a starting point of getting the data from your JSON object. 然后由您决定如何操作/持久化数据,但这应为您提供从JSON对象获取数据的起点。
Summary 摘要
Dictionary<string, object>
默认ModelBinder能够将JSON分配为C# Dictionary<string, object>
MyMethod
signature to accept Dictionary<string, object>
type for parameter
, or cast the parameter
object to a Dictionary
(both should work the same) 更改MyMethod
签名以接受parameter
Dictionary<string, object>
类型,或将parameter
对象转换为Dictionary
(两者都应工作相同) Dictionary
. 迭代Dictionary
每个项目。 You can then access the Key
s and Value
s of each item, and then manipulate the data however you wish 然后,您可以访问每个项目的Key
和Value
,然后根据需要操作数据 Furthermore 此外
Given that your JSON string is passing in key/value pairs of string
and string
, I suspect that you may safely use Dictionary<string, string>
to be picked up by the ModelBinder, or when casting etc. confirmation may be needed on this, however 鉴于您的JSON字符串正在传入string
和string
键/值对,我怀疑您可以安全地使用Dictionary<string, string>
由ModelBinder拾取,或者在进行强制转换等时。 可能需要对此进行确认,然而
Hope this helps, and best of luck in your project! 希望这会有所帮助,并为您的项目带来好运! :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.