我真的是JSON的新手,但這裏是我得到的。我需要創建一個包含數組/列表和一對平坦字段的對象。例如:構建,發送和反序列化一個包含數組的json對象
var names= new Array();
names[0] = "Christy";
names[1] = "Jeremy";
var obj = {
names: names,
age: "21+",
comment: "friends"
};
我那麼字符串化,並嘗試通過AJAX將其發送到一個PageMethod的:
var jsonData = JSON.stringify(obj);
sendData(obj);
然後發送:
function sendData(jsonData) {
$.ajax({
type: "POST",
url: "Default.aspx/TestArray",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('win');
},
error: function (a, b, ex) {
alert('fail');
}
});
}
這樣一起:
$(document).ready(function() {
$("#btnSubmit").click(function (e) {
e.preventDefault();
var names = new Array();
names[0] = "Christy";
names[1] = "Jeremy";
var obj = {
names: names,
age: "21+",
comment: "friends"
};
var jsonData = JSON.stringify(obj);
sendData(jsonData);
});
function sendData(jsonData) {
$.ajax({
type: "POST",
url: "Default.aspx/TestArray",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (a, b, ex) {
alert("oops: " + ex);
}
});
}
});
我不知道我是否在做這個權利。它甚至沒有進入webmethod,而是直接進入錯誤功能。但只是談話的緣故,這是我的代碼隱藏:
[WebMethod()]
public static string TestArray(string guids)
{
Comment cmt = (Comment)JsonConvert.DeserializeObject(guids, typeof(Comment));
return "Winner";
}
課程班IM,並試圖反序列化到:
public class Comment
{
public List<string> names { get; set; }
public string age { get; set; }
public string comment { get; set; }
}
請參閱[本答案](http:// stackoverflow。com/a/9084625/283366)獲取關於在原始郵件正文中發送JSON數據的信息 – Phil 2012-03-28 05:52:27