首页 > 解决方案 > 如何在asp.net c#中将json数据绑定到gridview?

问题描述

我想将JSON文件中的数据显示到gridview. 我设法解码了JSON文件,并试图与gridview.

但是,会弹出一个错误。

错误是:Newtonsoft.Json.JsonSerializationException:'读取 DataTable 时出现意外的 JSON 令牌。预期 StartArray,得到 StartObject。路径'',第 1 行,位置 1

JSON代码:

{
 "value":{

"Status": 2,
    "AffectedSegments": [
      {

        "Line": "NEL",
        "Direction": "HarbourFront",
        "Stations": "NE9,NE8,NE7,NE6", 
      "MRTShuttleDirection": "HarbourFront"}
      ,
      {
        "Line": "EWL",
        "Direction": "Simei", 
     "Stations": "NE9,NE8,NE7,NE6", 
    "MRTShuttleDirection": "HarbourFront"}],
    "Message": [
      {
        "Content": "0901hrs : NEL "
        "CreatedDate": "2018-03-16 09:01:53"
      }
    ]
  }
}

编码:

    public DataTable jsonDataDiplay()
    {
        StreamReader sr = new StreamReader(Server.MapPath("TrainServiceAlerts.json"));
        string json = sr.ReadToEnd();
        var table = JsonConvert.DeserializeObject<DataTable>(json);
        //DataSet ds = JsonConvert.DeserializeObject<Wrapper>(json).DataSet;
        return table;
    }

设计页面:

 <asp:GridView ID="GridView2" runat="server">
     <Columns>
         <asp:BoundField DataField="Line" HeaderText="Line" />
         <asp:BoundField DataField="Direction" HeaderText="Direction" />
          <asp:BoundField DataField="Stations" HeaderText="Stations" />
          <asp:BoundField DataField="MRTShuttleDirection" HeaderText="MRTShuttleDirection" />


     </Columns>
 </asp:GridView>

我不确定如何解决该错误。请帮助我并给我建议!我在 NE 之外添加了“。它从一开始就在我的 json 文件中,只是我没有正确复制到这里。

先感谢您!

标签: c#asp.netjsongridview

解决方案


首先:您的 JSON 示例无效:

"Message": [
  {
    "Content": "0901hrs : NEL  <- ", is missing 
    "CreatedDate": "2018-03-16 09:01:53"
  }
]

下一个问题是您不能将 json 直接反序列化为数据表。您的数据位于层次结构的深处,因此您必须做更多的工作来转换它:

public DataTable jsonDataDiplay()
{
    StreamReader sr = new StreamReader(Server.MapPath("TrainServiceAlerts.json"));
    string json = sr.ReadToEnd();
    dynamic table = JsonConvert.DeserializeObject(json);
    DataTable newTable = new DataTable();
    newTable.Columns.Add("Line", typeof(string));
    newTable.Columns.Add("Direction", typeof(string));
    newTable.Columns.Add("Stations", typeof(string));
    newTable.Columns.Add("MRTShuttleDirection", typeof(string));

    foreach (var row in table.value.AffectedSegments)
    {
        newTable.Rows.Add(row.Line, row.Direction, row.Stations, row.MRTShuttleDirection);
    }
    return newTable;
}

推荐阅读