C# 如何将JSON数据转换为对象?
我有一个JSON数组,如下所示:C# 如何将JSON数据转换为对象?,c#,json,asp.net-4.0,.class-file,C#,Json,Asp.net 4.0,.class File,我有一个JSON数组,如下所示: theFormData = {"FormNodeID":142365,"SubmissionMethod":"Desktop","ConfirmationEmailID":"142371","FirstName":"Solomon","LastName":"Closson","EmailAddress":"myemail@testing.com","Company":"TIF","JobTitle":"Web Developer"} FormNodeID,提交
theFormData = {"FormNodeID":142365,"SubmissionMethod":"Desktop","ConfirmationEmailID":"142371","FirstName":"Solomon","LastName":"Closson","EmailAddress":"myemail@testing.com","Company":"TIF","JobTitle":"Web Developer"}
FormNodeID
,提交方法
和确认邮件ID
将始终相同,但是,名字
,姓氏
,电子邮件地址
,公司
,和JobTitle
将作为字符串填充到JSON中,该字符串将根据管理员在标签中输入的值进行更改,并使用正则表达式删除特殊字符和空格
因此,我有代码将其填充到另一个变量中,称为theProperty
,然后将这些JSON对象添加到其中,如下所示:
theFormData[theProperty]=值代码>
其中值等于输入值。问题是,我需要能够将这个JSON变量传输到ASP.NET C#Class文件.cs
,并从JSON对象动态构建类属性。这可能吗
现在,我用以下代码将其发送给处理程序:
var formdata = 'formdata=' + encodeURIComponent(Sys.Serialization.JavaScriptSerializer.serialize(theFormData));
MakeRequest('/handlers/formshandler.ashx?f=formcontrol&r=' + Math.random(), 'POST', formdata, SaveComplete, null);
MakeRequest及其依赖函数如下所示:
function MakeRequest (url, verb, data, func, obj) {
try {
var TheRequest = new Sys.Net.WebRequest();
TheRequest.set_url(url);
TheRequest.set_httpVerb(verb);
if (data) {
TheRequest.set_body(data);
}
TheRequest.set_userContext(new RequestParamsNew(func, obj));
TheRequest.add_completed(MakeRequestComplete);
TheRequest.invoke();
return TheRequest;
}
catch (error) {
if (func) func('Communication Error');
}
}
function MakeRequestComplete (executer, eventArgs)
{
var TheParams = executer.get_webRequest().get_userContext();
if (executer.get_responseAvailable())
{
TheParams.responseData = executer.get_responseData().replace(/\u2028/g, '');
}
else
{
TheParams.responseData = null;
}
if (TheParams.func) TheParams.func(TheParams);
}
function RequestParamsNew(afunc, obj)
{
this.func = afunc;
this.responseData = null;
this.obj = obj;
this.Error = null;
}
function SaveComplete(params) {
if (params.responseData) {
var theItems = eval(Sys.Serialization.JavaScriptSerializer.deserialize(params.responseData, false));
if (theItems.Valid) {
// Redirect somewhere...
document.location.href = "http://www.google.com";
}
else {
$.each(theItems.Errors, function (idx, error) {
Console.Log(error);
});
}
}
}
这会将其传递给位于handlers/formhandler.ashx中的表单处理程序
在这个文件中,我检查f的请求,然后抓取发布的formdata
,如下所示:
CustomForm theCustomForm = new JavaScriptSerializer().Deserialize<CustomForm>(_Context.Request["formdata"]);
只是测试看看是否有任何错误
返回。我的SaveComplete函数如下所示:
function MakeRequest (url, verb, data, func, obj) {
try {
var TheRequest = new Sys.Net.WebRequest();
TheRequest.set_url(url);
TheRequest.set_httpVerb(verb);
if (data) {
TheRequest.set_body(data);
}
TheRequest.set_userContext(new RequestParamsNew(func, obj));
TheRequest.add_completed(MakeRequestComplete);
TheRequest.invoke();
return TheRequest;
}
catch (error) {
if (func) func('Communication Error');
}
}
function MakeRequestComplete (executer, eventArgs)
{
var TheParams = executer.get_webRequest().get_userContext();
if (executer.get_responseAvailable())
{
TheParams.responseData = executer.get_responseData().replace(/\u2028/g, '');
}
else
{
TheParams.responseData = null;
}
if (TheParams.func) TheParams.func(TheParams);
}
function RequestParamsNew(afunc, obj)
{
this.func = afunc;
this.responseData = null;
this.obj = obj;
this.Error = null;
}
function SaveComplete(params) {
if (params.responseData) {
var theItems = eval(Sys.Serialization.JavaScriptSerializer.deserialize(params.responseData, false));
if (theItems.Valid) {
// Redirect somewhere...
document.location.href = "http://www.google.com";
}
else {
$.each(theItems.Errors, function (idx, error) {
Console.Log(error);
});
}
}
}
但我得到了以下错误:
Sys.ArgumentException: Sys.ArgumentException: Cannot deserialize. The data does not correspond to valid JSON.
Parameter name: data
如果我将SaveComplete
功能中的items
部分更改为:
var theItems = params.responseData;
alert(theItems);
它会提醒以下内容(500页错误):
PHL
尝试{Typekit.load();}catch(e){}
1-800-CALL-PHL
错误500:内部服务器错误
由于内部(服务器软件)错误,服务器无法向您发送html文档
如果问题依然存在,请联系
这来自网站根目录中的500.htm文件。web.config文件中是否有我可能遗漏的东西需要为此执行
Sys.Serialization.JavaScriptSerializer.serialize(theFormData)
返回的JSON很好,因此它必须以反序列化的方式返回,可能?问题通过以下方法解决:
public void SubmitCustomForm()
{
List<string> theErrors = new List<string>();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var dict = serializer.Deserialize<Dictionary<string, string>>(_Context.Request["formdata"]);
foreach (KeyValuePair<string, string> pair in dict)
{
theErrors.Add(pair.Key + " = " + pair.Value);
}
_Context.Response.Write(new
{
Valid = theErrors.Count == 0,
Errors = theErrors,
Message = "Form Submitted"
}.ToJson());
}
public void SubmitCustomForm()
{
列出错误=新建列表();
var serializer=new System.Web.Script.Serialization.JavaScriptSerializer();
var dict=serializer.Deserialize(_Context.Request[“formdata”]);
foreach(dict中的KeyValuePair对)
{
错误。添加(pair.Key+“=”+pair.Value);
}
_Context.Response.Write(新建
{
Valid=theErrors.Count==0,
错误=错误,
Message=“表单已提交”
}.ToJson());
}
这验证非常好,没有错误。不确定为什么另一种方法不起作用,但这至少现在可以很好地工作,让我可以处理字典项…尝试Dictionary theCustomForm=new JavaScriptSerializer()。反序列化(_Context.Request[“formdata”])代码>棒极了,这似乎解决了没有错误!伟大的我将尝试使用字典而不是类文件。看起来很有希望!以前从未使用过字典。。。现在只需要弄清楚如何获取字典的值。干杯:)好吧,使用字典,我似乎无法从javascript中的处理程序获得所需的响应数据。。。我将用我正在使用的新代码编辑我的问题,也许有人可以帮助,因为它在jQuery$中返回为未定义。每个函数。好的,似乎有一个我忽略的问题,并将其删除,现在给了我以下信息:Sys.ArgumentException:Sys.ArgumentException:无法反序列化。数据与有效的JSON不对应。参数名称:data
可能params.responseData
已经是js对象。