2013-04-01 69 views
0

我在使用Kendo UI網格綁定我的JSON數據時遇到了困難,但在搜索此問題的解決方案時我遇到了另一個問題。那如何正確地解析JSON以匹配其正確的格式由@Petur Subev提到here.通過JsonTextWriter正確解析JSON

我現在的JSON的格式如下:

//{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null} 
//{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0} 

但正如指出它應該是這樣的:

[{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null}, 
{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0}, 
{"No":null,"Desc":"asfasfasfskfjklajsfkjasklfjklasjfklajsfkljaklsfjklasjfkljasfkljlasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0}] 

它很難理解,爲什麼它是這種方式,因爲我正在使用預構建函數來創建JSON,但我仍然錯誤地幫助。

Model Code

我有:

public object GetResult(string id) 
{ 
    var sqlCom = new SqlCommand("SELECT [No],[Desc],[Date],[Height],[Final] FROM [cr_form] WHERE [uId][email protected];", sqlConn); 
    sqlCom.Parameters.AddWithValue("@id", id); 

    StringBuilder sb = new StringBuilder(); 
    StringWriter sw = new StringWriter(sb); 
    JsonWriter jsonWriter = new JsonTextWriter(sw); 
    var rcrds = GETSQLRESULTS(sqlCom); 

    try 
    { 
     int i = 0; 
     if (rcrds != null || rcrds.HasRows) 
     { 
      //jsonWriter.WriteStartObject(); 
      while (rcrds.Read()) 
      { 
       jsonWriter.WriteStartObject(); //Changed 
       for (int j = 0; j < rcrds.FieldCount; j++) 
       { 
        jsonWriter.WritePropertyName(rcrds.GetName(j)); // column name 
        jsonWriter.WriteValue(rcrds.GetValue(j)); // value in column 
       } 
       i++; 
       jsonWriter.WriteEndObject(); //Changed 
      } 
      //jsonWriter.WriteEndObject(); 

     } 

    } 

    catch (Exception ex) { } 
    return jsonWriter; 
} 

Controller

public ActionResult GetRecords() 
{ 
    var usrObj = new User(); 
    var jsnRslt = usrObj.GetResult(Session["Id"].ToString()); 

//After Changes in the Model I am getting it in the required Array format: 
//{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null} 
//{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0} 
//{"No":null,"Des... 

    return Json(jsnRslt, JsonRequestBehavior.AllowGet);    
} 

添加WriteStartArray();

{[{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null}, 
{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0}, 
{"No":null,"Desc":"asfasfasfskfjklajsfkjasklfjklasjfklajsfkljaklsfjklasjfkljasfkljlasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0}, 
{"No":null,"Desc":"hdfhdfhdfh","Date":"2013-04-04T00:00:00","Height":1,"Final":0}]} 

回答

4

爲什麼你在調用getResult方法構建JSON?你爲什麼寫這樣的管道代碼而不是把它留給框架?

你應該關注的是你的業務邏輯。

只要定義一個模型,表示要返回的數據(你可能需要調整的類型取決於列類型在你的數據庫模型的屬性):

public class MyModel 
{ 
    public int? No { get; set; } 
    public string Desc { get; set; } 
    public DateTime Date { get; set; } 
    public int? Height { get; set; } 
    public int? Final { get; set; } 
} 

,然後讓方法返回該模型(實際上是一個收集這種模式的更精確):

public IEnumerable<MyModel> GetResult(string id) 
{ 
    string connectionString = "..."; 
    using (var conn = new SqlConnection(connectionString)) 
    using (var cmd = conn.CreateCommand()) 
    { 
     conn.Open(); 
     cmd.CommandText = "SELECT [No],[Desc],[Date],[Height],[Final] FROM [cr_form] WHERE [uId][email protected];"; 
     cmd.Parameters.AddWithValue("@id", id); 
     using (var reader = cmd.ExecuteReader()) 
     { 
      while (reader.Read()) 
      { 
       yield return new MyModel 
       { 
        No = GetValue(reader, "No"), 
        Desc = reader.GetString(reader.GetOrdinal("Desc")), 
        Date = reader.GetDateTime(reader.GetOrdinal("Date")), 
        Height = GetValue(reader, "Height"), 
        Final = GetValue(reader, "Final"), 
       }; 
      } 
     } 
    } 
} 

private static int? GetValue(DbDataReader reader, string columnName) 
{ 
    var columnIndex = reader.GetOrdinal(columnName); 
    if (!reader.IsDBNull(columnIndex)) 
    { 
     return reader.GetInt32(columnIndex); 
    } 
    return null; 
} 

注意我是如何已經刪除了TR /捕獲邏輯,因爲你沒有做的catch語句有用的東西,這是一個糟糕的想法,默默地消耗這樣的例外。

最後在你的控制器操作簡單:

public ActionResult GetRecords() 
{ 
    var usrObj = new User(); 
    var jsnRslt = usrObj.GetResult(Session["Id"].ToString()); 
    return Json(jsnRslt, JsonRequestBehavior.AllowGet); 
} 

正如你可以看到在這個例子你不應該擔心管道和JSON。你應該使用強類型模型,並讓框架爲你做序列化。

+0

Thakyou提出這個建議,工作。 :) – Maven

1

看起來你只是想打電話給0123後在開始...

示例代碼:

using System; 
using Newtonsoft.Json; 

class Test 
{ 
    static void Main() 
    { 
     using (var writer = new JsonTextWriter(Console.Out)) 
     { 
      writer.WriteStartArray(); 
      for (int i = 0; i < 5; i++) 
      { 
       writer.WriteStartObject(); 
       writer.WritePropertyName("Foo"); 
       writer.WriteValue(i); 
       writer.WriteEnd(); 
      } 
      writer.WriteEnd(); 
     } 
    } 
} 

輸出:

[{"Foo":0},{"Foo":1},{"Foo":2},{"Foo":3},{"Foo":4}] 
+0

做到了這一點,我想我已經得到了理想的結果..我只是困惑了一點,那爲什麼我在開始和結束'''開始括號'{''''。這是好的還是錯的。我更新了我的問題,好心一看,看看新的JSON。 – Maven

+0

@Maven:我懷疑'Json'方法本身就是將你的數組封裝在一個對象中 - 所以你返回一個包含數組的對象,而不僅僅是一個數組。鑑於您首先調用了Json方法,您是否肯定需要自己完成其餘的JSON編碼?正如達林所說,你應該能夠回收一​​個集合。 –