2013-10-03 57 views
1

我試圖使用Newtonsoft.JSON將DataTable轉換爲JSON,但發現輸出不是ExtJS網格和圖表所期望的。使用Json轉換DataTable時使用Json格式無效使用Json.Net

我的代碼是

string output = JsonConvert.SerializeObject(dt, Formatting.Indented, 
          new JsonSerializerSettings 
          { 
           ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
          }); 

,這將返回JSON字符串作爲

"[{\"DAYDATE\":\"2012-05-22T00:15:00\",\"SERIES1\":3.65}]" 

如果我刪除 '\',並開始和結束它正常工作與ExtJS的雙引號。

我也試過在

"[{\"DAYDATE\":new Date(1337642100000),\"SERIES1\":3.65}]" 

改變日期格式更JSON'y

string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter()); 

結果仍然沒有運氣

+0

忘了補充ExtJS的電網拋出錯誤200 –

回答

2

它看起來像你的JSON越來越雙系列化。你雖然沒有顯示完整的控制器代碼,我猜,你正在做這樣的事情:

public ActionResult GetDataTable() 
    { 
     // (... code to build data table omitted for brevity ...) 

     // Serialize data table using Json.Net to avoid circular reference error 
     string output = JsonConvert.SerializeObject(dt, 
      new JsonSerializerSettings 
      { 
       ReferenceLoopHandling = ReferenceLoopHandling.Ignore, 
       Formatting = Formatting.Indented 
      }); 

     return Json(output); 
    } 

Json()方法還調用序列化。通常,在MVC控制器中,您只需使用Json()方法來序列化返回對象,而不是單獨使用Json.Net。我可以看到你在這裏使用Json.Net來嘗試解決當你嘗試序列化數據表時由於循環引用而發生的異常。如果您要手動序列化,那麼您需要以不會再次序列化的方式返回數據。您可以使用Content()方法代替。試着這樣說:

public ActionResult GetDataTable() 
{ 
    // Build data table 
    DataTable dt = new DataTable(); 
    dt.Columns.Add("DAYDATE", typeof(DateTime)); 
    dt.Columns.Add("SERIES1", typeof(double)); 
    dt.Rows.Add(new DateTime(2012, 5, 22, 0, 15, 0), 3.65); 

    // Serialize data table using Json.Net to avoid circular reference error 
    string output = JsonConvert.SerializeObject(dt, 
     new JsonSerializerSettings 
     { 
      ReferenceLoopHandling = ReferenceLoopHandling.Ignore, 
      Formatting = Formatting.Indented 
     }); 

    // Output is already serialized; return it as is (with the appropriate media type) 
    return Content(output, "application/json"); 
} 

在我的測試中,上面會產生下面的輸出,我認爲這是你在找什麼:

[ { "DAYDATE": "2012-05-22T00:15:00", "SERIES1": 3.65 } ] 
+0

我嘗試直接返回dataTable,但我得到循環引用錯誤。在序列化'System.Reflection.RuntimeModule'類型的對象時檢測到循環引用'「 –

+0

您的控制器是繼承自Controller還是ApiController? –

+0

它是繼承自'Controller' –

相關問題