2016-09-16 34 views
-1

公共類的一部分我爲dataTables插件構建了一個數據結構。C#將字符串轉換爲JSON錯誤

構建數據結構中的代碼是:

 var response = "{ \"data\": ["; 
      response = response + "["; 
      response = response + "\"Clark, Keith\","; 
      response = response + "\"Corporate\","; 
      response = response + "\"XXX-XXX-XXXX\","; 
      response = response + "\"XXX-XXX-XXXX\","; 
      response = response + "\"[email protected]\""; 
      response = response + "],"; 
      response = response + "["; 
      response = response + "\"Clark, Keith\","; 
      response = response + "\"Corporate\","; 
      response = response + "\"YYY-YYY-YYYY\","; 
      response = response + "\"YYY-YYY-YYYY\","; 
      response = response + "\"[email protected]\""; 
      response = response + "]"; 
     response = response + "] }"; 

     return response; 

此運行良好並創建表按預期方式。我遇到的問題是當我嘗試將HTML標記添加到字段時。我想使用的字體真棒圖標旁邊的名稱來表示這樣的狀態:

<i class="fa fa-arrow-up" style="color: #00ff00;" aria-hidden="true"> 

我試圖修改我的代碼如下:

response = response + "\"<i class=\"\"fa fa-arrow-up\"\" style=\"\"color: #00ff00;\"\" aria-hidden=\"\"true\"\">Clark, Keith\","; 

但現在我收到了一條錯誤的JSON格式不正確。我是否錯過了某些東西,或者HTML標記不能在JSON結構中使用?

+0

你不會錯過任何東西,html標記是無效的JSON。 JSON字符串必須完全獨立。 –

+0

發佈帶有新東西的json。在最後關閉之後,你是不是想添加它? – Dispersia

+0

@JonathonChase html中沒有任何問題,html只是靜態文本,這正是JSON擅長的。 – Dispersia

回答

0

問題是你正在生成一個無效的json字符串文字。

"<i class=""fa fa-arrow-up"" style=""color: #00ff00;"" aria-hidden=""true"">Clark, Keith", 

引號使用字面反斜槓轉義,而不是加倍。

你將不得不這樣做,而不是:

"\"<i class=\\\"fa fa-arrow-up\\\" style=\\\"color: #00ff00;\\\" aria-hidden=\\\"true\\\">Clark, Keith\"," 

這說明到底爲什麼你不應該產生這樣的字符串。有些工具可以爲你安全地使用它們。 Json.net可以輕鬆解決這個問題。

var markup = "<i class=\"fa fa-arrow-up\" style=\"color: #00ff00;\" aria-hidden=\"true\">"; 
var response = new JObject 
{ 
    ["data"] = new JArray 
    { 
     new JArray 
     { 
      markup + "Clark, Keith", 
      "Corporate", 
      "XXX-XXX-XXXX", 
      "XXX-XXX-XXXX", 
      "[email protected]", 
     }, 
     new JArray 
     { 
      markup + "Clark, Keith", 
      "Corporate", 
      "YYY-YYY-YYYY", 
      "YYY-YYY-YYYY", 
      "[email protected]", 
     }, 
    } 
}; 
return response.ToString(); 

隨着中說,你不應該添加標記您的數據。數據只是數據而已,僅此而已。如果您想要影響它的顯示方式,那麼應該將該標記添加到您的視圖中。