c# - 如何在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 文件中,只是我没有正确复制到这里。
先感谢您!
解决方案
首先:您的 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;
}
推荐阅读
- angular - 如何使用 mergeMap 对链式请求进行单元测试
- r - 使用整个数据集在线性回归图上绘制数据的子部分
- monitoring - 在无主架构中使用 zookeeper 有意义吗?
- python - 每次重新启动程序后,Python Tkinter 的渲染速度都会变慢
- wpf - WPF 应用程序在 Jenkins 服务中运行但不是作为普通用户时崩溃
- java - Java8+:将匿名对象传递给方法
- amazon-web-services - 手动管理 SQS 队列与 Lambda 触发器
- c - 卸载 LD_PRELOAD 而不重启进程
- c# - 在 UWP 中加载 WebView 时应用程序无响应
- pandas - 返回 dtype bool 系列中最后一次出现的 True