2017-08-28 44 views
1

我正在嘗試使用AJAX從客戶端向服務器發送JSON對象。我想採用JSON並將其序列化爲xml並將其存儲在SQL Server中。使用JSON.Net從JSON序列化到XML的問題 - C#

我進行POST和使用發送JSON作爲一個字符串:

var Full_JSON = products_json[product_id]; 
    var Message = ""; 

    if (FULL_JSON == null) { 
     Message = "No Products_JSON!"; 
    } 

    if (Message.length == 0) { 
     $.ajax({ 
      type: "POST", 
      dataType: "json", 
      contentType: "application/json; charset=utf-8", 
      url: "/Query.asmx/InsertXMLJSON", 
      data: "{'JSON':'" + JSON.stringify(Full_JSON) + "'}", 
      success: function (Record) { 
       if (Record.d == true) { 
        console.log("AJAX Success: " + JSON.stringify(Record)); 
       } 
       else { 
        console.log("AJAX Fail: " + JSON.stringify(Record)); 
       } 
      }, 
      error: function (XMLHttpRequest, textStatus, errorThrown) { 
       console.log("Status: " + textStatus); 
       console.log("Error: " + errorThrown); 
      } 
     }) 
    } 

然後我去傳遞了「JSON」字符串,並呼籲:

public static bool InsertXMLJSON(string UserEmail, string Time, string Product, string JSON) 
{ 
    System.Xml.XmlDocument xmlJSON = JsonConvert.DeserializeXmlNode(JSON, "root"); 
} 

當這個被稱爲我得到以下異常:

解析值後遇到意外的字符:問:路徑 「Calculations.1.Calculation_Logic」,1號線,位置4167.

這裏是JSON字符串的一個片段,其中遇到的字符:

\"Calculation_Logic\":\"Math.round((products_json[product_id][\"Questions\"][1][\"Answer\"])/(products_json[product_id][\"Questions\"][3][\"Answer\"]))\" 

我已經注意到,報價轉義在方括號內似乎是問題的一部分。如果我刪除引號,它就可以解析它。

任何想法,爲什麼這會造成問題?

回答

0

在我看來,你串起簡單的字符串變量稱爲Full_JSON。你試圖發送它而不是JSON.stringify(Full_JSON)?如果沒有完整的代碼示例,很難理解你究竟是什麼字符串,但這可能是原因。例如:

var str = '{"2003":{"1":{"2":["test"],"3":["test2"]}}}'; 
var obj = {"2003":{"1":{"2":["test"],"3":["test2"]}}}; 

//this one looks very similar to your problem 
console.log(JSON.stringify(str)); // {\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}} 

//and this one is correct use of this component 
console.log(JSON.stringify(obj)); // {"2003":{"1":{"2":["test"],"3":["test2"]}}} 
+0

感謝您的建議。我已經上傳了AJAX的代碼片段。我直接在JSON對象上調用JSON.stringify。 – tremarkley