如何将JSON数据转换为对象

本文关键字:转换 对象 数据 JSON | 更新日期: 2023-09-27 17:54:58

我有一个JSON数组,像这样:

theFormData = {"FormNodeID":142365,"SubmissionMethod":"Desktop","ConfirmationEmailID":"142371","FirstName":"Solomon","LastName":"Closson","EmailAddress":"myemail@testing.com","Company":"TIF","JobTitle":"Web Developer"}

FormNodeID, SubmissionMethodConfirmationEmailID将始终是相同的,然而,FirstName, LastName, EmailAddress, CompanyJobTitle正在用javascript作为字符串填充到JSON中,该字符串将根据管理员放入标签的值更改,并使用正则表达式删除特殊字符和空格。

因此,我有代码将其填充到另一个变量theProperty中然后我将这些JSON对象添加到它中,如下所示

theFormData[theProperty] = value;

,其中value等于输入值。问题是,我需要能够将这个JSON变量转换为ASP。. NET c#类文件.cs,并从JSON对象动态构建类属性。这可能吗?

现在我用下面的代码将它发送给Handler:

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;
}

将它传递给位于handlers/formhandler.ashx

中的Form Handler

在这个文件中,我检查f的请求,然后像这样抓取发布的formdata:

CustomForm theCustomForm = new JavaScriptSerializer().Deserialize<CustomForm>(_Context.Request["formdata"]);

所以CustomForm是一个类文件,我需要能够准确地从formdata JSON变量填充属性。这个似乎做不到。似乎能够获得值,但我必须在CustomForm.cs文件中手动输入。cs文件中设置公共属性。但是,我需要它根据JSON自动创建属性,因为不同的表单的属性很可能是不同的。

这怎么可能?

编辑

好的,所以现在使用Dictionary<string, string>代替类,根据注释。

在处理程序中,现在使用以下代码:

List<string> theErrors = new List<string>();
Dictionary<string, string> theCustomForm = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(_Context.Request["‌​formdata"]);
foreach (KeyValuePair<string, string> pair in theCustomForm)
{
    theErrors.Add(pair.Key + " = " + pair.Value);
}
_Context.Response.Write(new
{
    Valid = theErrors.Count == 0,
    Errors = theErrors,
    Message = "Form Submitted"
}.ToJson());

只是测试看看是否有任何Errors返回。我的SaveComplete函数看起来像这样:

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函数中的theItems部分更改为:

var theItems = params.responseData;
alert(theItems);

提示以下内容(500 Page Error):

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
  <title>PHL</title>
  <meta name="description" content="" />
  <meta name="keywords" content="" />
  <meta name="format-detection" content="telephone=no" />
  <meta name="viewport" content="width=1024" />
  <meta charset="utf-8" />
  <link rel="shortcut icon" href="/media/1606636/homestead_favicon.ico" type="image/x-icon" />
  <link rel="stylesheet" href="/scripts/jquery-select2/select2.css" />
  <!-- <link rel="stylesheet" href="styles/bootstrap.css" /> -->
  <link rel="stylesheet" href="/styles/datepicker.css" />
  <link rel="stylesheet" href="/styles/styles.css" />
  <script type="text/javascript" src="//use.typekit.net/qrs7pfm.js"></script>
  <script type="text/javascript">      try { Typekit.load(); } catch (e) { }</script>
  <script type="text/javascript" src="/scripts/BaseUI.js"></script>
</head>
<body>
  <div class="var-nav" style="display: none;"></div>
  <div id="Container" class="secondary">
    <!-- Header -->
    <div class="header-elements clearfix">
      <div class="header-row row">
        <header class="header container">
          <div class="main-nav nav-small">
            <div class="clearfix">
              <nav>
                <ul class="nav-buttons">
                  <li class="phl-logo"><a href="/">PHL</a></li>
                  </li>
                </ul>
              </nav>      
            </div>
          </div>
        </header>
      </div>
      <div id="call-phl">1-800-CALL-PHL</div>
    </div>
    <!-- .Header -->

    <div id="hero-slideshow" class="hero-slideshow">
      <div class="slides">
        <div class="slide">
          <img src="/images/SAMPLE_slide-grad-bg.jpg" alt="" />
        </div>
      </div>
    </div>
    <div class="page tertiary bg_pattern">
      <div class="">
        <div class="row-inner breadcrumbs-row">
            <ul class="breadcrumbs clearfix">
            <li><a href="/">Home</a></li>
            <li>Error 500</li>
          </ul>        
        </div>          
        <div class="row-inner bg_pattern">
            <h1>Error 500: Internal Server Error</h1>
            <!-- Right Rail Column -->
            <div class="right-rail clearfix">
            <div class="body article-body">            
                <div class="article container">                
                <p>The server was unable to send the html document to you due to an internal (server software) error.</p>
                <p>If the issue persists, contact <a href="#">webmaster@discoverPHL.com</a></p>
              </div>
            </div>
            <div class="rail">
            </div>
          </div>
            <!-- Right Rail Column -->
        </div>
      </div>
    </div>

  </div>
  <!-- .Footer -->
</div>
</body>
</html>

这是来自网站根目录下的500.htm文件。网上有什么东西吗?需要为此做的配置文件,我可能错过了?

Sys.Serialization.JavaScriptSerializer.serialize(theFormData)返回JSON很好,所以它必须在它被反序列化的方式也许?

如何将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());            
}

这完全可以验证,没有错误。不知道为什么另一种方法不起作用,但这至少现在工作完美,让我可以处理字典项…