2014-03-29 16 views
0

我有一個JSON數組像這樣:如何將JSON數據轉換爲對象?

theFormData = {"FormNodeID":142365,"SubmissionMethod":"Desktop","ConfirmationEmailID":"142371","FirstName":"Solomon","LastName":"Closson","EmailAddress":"[email protected]","Company":"TIF","JobTitle":"Web Developer"} 

FormNodeIDSubmissionMethod,和ConfirmationEmailID將始終是相同的,然而,FirstNameLastNameEmailAddressCompany,和JobTitle被填充到JSON與JavaScript作爲字符串將根據管理員放入標籤的值而改變,並使用正則表達式來刪除特殊字符和空格。

所以,我有填充到另一個變量,叫theProperty這段代碼比我這些JSON對象添加到它像這樣:

theFormData[theProperty] = value;

其中值等於輸入值。事情是,我需要能夠將此JSON變量轉換爲ASP.NET C#類文件.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; 
} 

這它傳遞到位於表單處理程序處理程序/ formhandler.ashx

在這個文件中,我檢查f的請求,並抓取發佈的formdata,如下所示:

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

因此,CustomForm是一個Class文件,我需要能夠從formdata JSON變量中精確填充屬性。這似乎並沒有這樣做。它似乎能夠獲取值,但我必須在.cs文件中手動輸入CustomForm.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頁錯誤):

<!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="#">[email protected]</a></p> 
       </div> 
      </div> 
      <div class="rail"> 
      </div> 
      </div> 
      <!-- Right Rail Column --> 
     </div> 
     </div> 

    </div> 


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

這是來自網站根目錄中的500.htm文件。有沒有什麼需要在web.config文件中完成,因此我可能錯過了?

Sys.Serialization.JavaScriptSerializer.serialize(theFormData)返回JSON就好了,所以它必須以它被反序列化的方式呢?

+2

嘗試'字符串,字符串> theCustomForm = new JavaScriptSerializer()。反序列化<字典<字符串,字符串>>(_ Context.Request [「formdata」]);' – Grundy

+0

太棒了,這似乎解決沒有錯誤!大!要嘗試使用Dictionary而不是Class文件。看起來很有前途!從來沒有使用過一個字典......只需要弄清楚如何獲取字典的值現在。乾杯:) –

+0

那麼,使用字典,我似乎無法得到我需要從JavaScript內的處理程序的responseData ...我將編輯我的問題與我使用的新代碼,也許有人可以幫助,導致它在jQuery'$ .each'函數中未定義。 –

回答

1

問題得到解決下列要求:

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

這驗證,沒有錯誤完美的罰款。不知道爲什麼其他方法不起作用,但這至少現在完美的作品,讓我處理字典項目...