如何使用ASP.NET反序列化JavaScript数组

时间:2012-06-28 20:41:42

标签: c# javascript jquery asp.net json

我有以下JavaScript代码:

var x = ['CFMG','JMFMG','CPMAF'];
var y = $.param({'test':x});
var data = "Operation=xxx&" + y;
$.post(
    "xxx.ashx",
    data,
    function() { ... }
);

Chrome console.log(data)

Operation=xxx&test%5B%5D=4CFMG&test%5B%5D=JMFMG&test%5B%5D=CPMAF 

我的ASP.NET代码正在接收:

{Operation=xxx&test%5b%5d=4CFMG&test%5b%5d=JMFMG&test%5b%5d=CPMAF}
[System.Web.HttpValueCollection]: {Operation=xxx&test%5b%5d=4CFMG&test%5b%5d=JMFMG&test%5b%5d=CPMAF}
base {System.Collections.Specialized.NameObjectCollectionBase}: {Operation=xxx&test%5b%5d=4CFMG&test%5b%5d=JMFMG&test%5b%5d=CPMAF}
AllKeys: {Dimensions:[2]}

AllKeys

{Dimensions:[2]}
[0]: "Operation"
[1]: "test[]"

在立即窗口中,如果我输入?var["Test[]"],我会得到:

?var["Test[]"]
"4CFMG,JMFMG,CPMAF"

如何将Test[]值转换为数组?

谢谢!

2 个答案:

答案 0 :(得分:2)

将您的javascrpt数组转换为json对象,然后将数据发布到服务器。我建议你使用JSON.NET。它是一个开源库,用于将c#对象序列化和反序列化为json,反之亦然...

例如:

string json = @"{
  ""Name"": ""Apple"",
  ""Expiry"": new Date(1230422400000),
  ""Price"": 3.99,
  ""Sizes"": [
    ""Small"",
    ""Medium"",
    ""Large""
  ]
}";

JObject o = JObject.Parse(json);

string name = (string)o["Name"];
// Apple

JArray sizes = (JArray)o["Sizes"];

string smallest = (string)sizes[0];

答案 1 :(得分:1)

我改变了我的JavaScript代码,现在没问题。

我使用JSON.stringify将JavaScript数组解析为字符串并将其发送到ASP.NET。

新的JavaScript代码:

var x = ['CFMG','JMFMG','CPMAF'];
var y = JSON.stringify(x);
var data = "Operation=xxx&test=" + y;
$.post(
    "xxx.ashx",
    data,
    function() { ... }
);

Chrome console.log(data)

Operation=xxx&test=["4CFMG","JMFMG","CPMAF"]

我的ASP.NET代码现在收到了这个:

{Operation=xxx&test=%5b%224CFMG%22%2c%22JMFMG%22%2c%22CPMAF%22%5d}
[System.Web.HttpValueCollection]: {Operation=xxx&test=%5b%224CFMG%22%2c%22JMFMG%22%2c%22CPMAF%22%5d}
base {System.Collections.Specialized.NameObjectCollectionBase}: {Operation=xxx&test=%5b%224CFMG%22%2c%22JMFMG%22%2c%22CPMAF%22%5d}
AllKeys: {Dimensions:[2]}

AllKeys

{Dimensions:[2]}
[0]: "Operation"
[1]: "test"

在立即窗口中,如果我输入?vari["test"],我会得到:

?vari["test"]
"[\"4CFMG\",\"JMFMG\",\"CPMAF\"]"

转换为数组的ASP.Net代码

string[] blah = json.Deserialize<string[]>(vari["test"]);

立即窗口:?blah

?blah
{Dimensions:[3]}
[0]: "4CFMG"
[1]: "JMFMG"
[2]: "CPMAF"

非常感谢!