[英]How to bind json data to gridview in asp.net c#?
I wanted to display the data from JSON
file to the gridview
.我想将
JSON
文件中的数据显示到gridview
。 I've managed to decode the JSON
file and I was trying to bind with the gridview
.我设法解码了
JSON
文件,并试图与gridview
绑定。
However, an error pops out.但是,会弹出一个错误。
The error is: Newtonsoft.Json.JsonSerializationException: 'Unexpected JSON token when reading DataTable.
错误是:Newtonsoft.Json.JsonSerializationException: 'Unexpected JSON token when reading DataTable。 Expected StartArray, got StartObject.
预期的 StartArray,得到 StartObject。 Path '', line 1, position 1
路径 '',第 1 行,位置 1
The JSON
code: 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"
}
]
}
}
The code:编码:
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;
}
The design page:设计页面:
<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>
I'm not sure how to solve the error .我不确定如何解决错误。 Please, help me and advise me!
请帮助我并给我建议! i have added " besides NE. It was there from the start in my json file just tht i didnt copy correctly here.
我已经添加了“除了 NE。它从一开始就在我的 json 文件中,只是我没有在这里正确复制。
Thank you in advance!先感谢您!
First of all: Your JSON sample is not valid:首先:您的 JSON 示例无效:
"Message": [
{
"Content": "0901hrs : NEL <- ", is missing
"CreatedDate": "2018-03-16 09:01:53"
}
]
Next problem is the that you can not deserialize your json directly to a datatable.下一个问题是您无法将 json 直接反序列化为数据表。 Your data sits deep inside the hierachical structure, so you have to do a bit more work to convert this:
您的数据位于层次结构的深处,因此您必须做更多的工作来转换它:
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;
}
This is a sample code that you need i think.
这是我认为您需要的示例代码。
//Random json string, No fix number of columns or rows and no fix column name.
string myDynamicJSON = "[{'Member ID':'00012','First Name':'Vicki','Last Name':'Jordan','Registered Email':'vicki.j @tacinc.com.au','Mobile':'03 6332 3800','MailSuburb':'','MailState':'','MailPostcode':'','Engagement':'attended an APNA event in the past and ventured onto our online education portal APNA Online Learning','Group':'Non-member'},{'Member ID':'15072','First Name':'Vicki','Last Name':'Jordan','Registered Email':'vicki.j @tacinc.com.au','Mobile':'03 6332 3800','MailSuburb':'','MailState':'','MailPostcode':'','Engagement':'attended an APNA event in the past and ventured onto our online education portal APNA Online Learning','Group':'Non-member'}]";
//Using dynamic keyword with JsonConvert.DeserializeObject, here you need to import Newtonsoft.Json
dynamic myObject = JsonConvert.DeserializeObject(myDynamicJSON);
//Binding gridview from dynamic object
grdJSON2Grid.DataSource = myObject;
grdJSON2Grid.DataBind();
//Using DataTable with JsonConvert.DeserializeObject, here you need to import using System.Data;
DataTable myObjectDT = JsonConvert.DeserializeObject<DataTable>(myDynamicJSON);
//Binding gridview from dynamic object
grdJSON2Grid2.DataSource = myObjectDT;
grdJSON2Grid2.DataBind();
As a start you need to validate your JSON.首先,您需要验证您的 JSON。
I used this site to validate it which gave a pretty decent error message on to where your problem is我用这个网站来验证它,它给出了一个相当不错的错误信息,说明你的问题在哪里
https://jsonlint.com/ https://jsonlint.com/
Error: Parse error on line 20:
...": [{ "Content": "0901hrs : NEL "
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
This should be your starting point on fixing this.这应该是您解决此问题的起点。
I used the validator and a bit of research and found your issue is the following我使用了验证器和一些研究,发现您的问题如下
"Content": "0901hrs: NEL",
"CreatedDate": "2018-03-16 09:01:53"
YOUR json seems to be incorrectly formatted ", adding this sorted validation.您的 json 格式似乎不正确”,添加了此排序验证。
From there i would also recommend using objects in c# for reading this file从那里我还建议使用 c# 中的对象来读取此文件
to create these objects id suggest using this site创建这些对象 id 建议使用此站点
http://json2csharp.com/ http://json2csharp.com/
this will convert any working json to c# objects which you can then read into这会将任何工作 json 转换为 c# 对象,然后您可以将其读入
after fixing the issue this is how it will look once you have the objects解决问题后,这就是拥有对象后的外观
public class AffectedSegment
{
public string Line { get; set; }
public string Direction { get; set; }
public string Stations { get; set; }
public string MRTShuttleDirection { get; set; }
}
public class Message
{
public string Content { get; set; }
public string CreatedDate { get; set; }
}
public class Value
{
public int Status { get; set; }
public List<AffectedSegment> AffectedSegments { get; set; }
public List<Message> Message { get; set; }
}
public class RootObject
{
public Value value { get; set; }
}
From here you should be able to read the json into rootobject从这里你应该能够将 json 读入 rootobject
StreamReader sr = new StreamReader(Server.MapPath("TrainServiceAlerts.json"));
string json = sr.ReadToEnd();
var table = JsonConvert.DeserializeObject<RootObject>(json);
and then to bind the item to the grid simply do this然后将项目绑定到网格只需执行此操作
MyGridView.DataSource = RootObject
MyGridView.DataBind()
first of all your json is not well formed, at least in the question, i can't edit it as it is only missing a ",
at line 21. Now to get to your problem, DeserializeObject<>()
can't chew everything you throw at it, most of the times you would create a standalone class and pass that as the type, but in your use case, I can tell that you want to display the first array so you can get it with this:首先,您的 json 格式不正确,至少在问题中,我无法编辑它,因为它仅在第 21 行缺少一个
",
。现在要解决您的问题, DeserializeObject<>()
无法咀嚼你扔给它的所有东西,大多数时候你会创建一个独立的类并将它作为类型传递,但在你的用例中,我可以告诉你想要显示第一个数组,这样你就可以得到它:
var jsonLinq = JObject.Parse(json);
// Find the first array using Linq
var srcArray = jsonLinq.Descendants().Where(d => d is JArray).First();
var trgArray = new JArray();
foreach (JObject row in srcArray.Children<JObject>())
{
var cleanRow = new JObject();
foreach (JProperty column in row.Properties())
{
// Only include JValue types
if (column.Value is JValue)
{
cleanRow.Add(column.Name, column.Value);
}
}
trgArray.Add(cleanRow);
}
return JsonConvert.DeserializeObject<DataTable>(trgArray.ToString());
NewtonSoft was expecting the first thing it finds in the json, to be an array, not a single object. NewtonSoft 期望它在 json 中找到的第一件事是一个数组,而不是单个对象。
Expecting something like:期待类似的东西:
[ <-- ARRAY STARTS
{"a":"a"},
{"a":"b"}
]
If your json will always look like what you posted, and it's actually only a small sub-part of it that you want to break down to a datatable, you'll need to dig that out first如果您的 json 总是看起来像您发布的内容,并且实际上只是您想要分解为数据表的一小部分,则您需要先将其挖掘出来
Alternatively, you can use some service like quicktype.io to create a set of classes that represent your json, so you can parse it into those classes, and use that as your datasource或者,您可以使用诸如 quicktype.io 之类的服务来创建一组代表您的 json 的类,以便您可以将其解析为这些类,并将其用作您的数据源
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.