下面的代码应该可以帮助某人启动和运行。
上面的代码会导致错误,因为字符串没有默认构造函数。如果从 JSON.stringify() 客户端 JavaScript 方法传入字符串,如果传入的对象映射到对象中的公共字段,则第二个反序列化可能会起作用。
让我们看一个假设 .ASHX 文件接收来自 jQuery 调用的请求的快速示例,如下所示:
//Called from with a jQuery ready() in a simple html page
var getNewPerson = function ()
{
var NewPerson = new Object();
NewPerson.PersonID = "0";
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();
var arrObj;
var str = "";
var webMethod = "http://someserver.com/admin/DataHandler.ashx";
$.ajax({
cache: false,
url: webMethod,
type: "POST",
dataType: "json",
/* for hashtable or .net web service - data: "{\"NewPerson\":" + JSON.stringify(NewPerson) + "}", */
data: JSON.stringify(NewPerson),
contentType: "application/json; charset=utf-8"
}
)
.done( function(){}... code here ...etc)
//Valid JSON object format: {"PersonID":"1","FirstName":"Rick","LastName":"Wright","Address":"4520 No Such address Ave.","City":"Riverside","State":"CA","Zip":"92503"}
//And here is a sample class on the C# side in the .ashx handler page.
public class NewPerson
{
public int PersonID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
} // EOC Person
// 并在处理请求
public void ProcessRequest(HttpContext context)
{
string jsonString = "";
string rawJson = "";
System.Diagnostics.Debugger.Break();
HttpContext.Current.Request.InputStream.Position = 0;
string responseString;
var jsonSerializer = new JavaScriptSerializer();
/*Set the stream position to 0 */
context.Request.InputStream.Position = 0;
using (System.IO.StreamReader inputStream = new StreamReader(context.Request.InputStream))
{
rawJson = inputStream.ReadToEnd();
}
var objNewPerson = jsonSerializer.Deserialize<NewPerson>(rawJson);
if (clientList != null)
{
responseString = objNewPerson.FirstName + " " + objNewPerson.LastName ;
}
else
resp="No Record Found";
} // eof ProcessRequest