【发布时间】:2023-03-22 00:45:02
【问题描述】:
我想知道如何将服务器返回的 JSON 数据显示到 GridView 中。
我已反序列化 JSON 数据并存储在变量中,但无法在 Grid 中显示数据。
所以请有人帮我在 Grid 中显示数据。
我的代码:
protected void btn_ShowCust_Click(object sender, EventArgs e)
{
try
{
string url = clsGuid.GetAPI() + "/service/service/student/search/" + txtstuname.Text.Trim();
HttpWebRequest reque = (HttpWebRequest)HttpWebRequest.Create(url);
reque.Method = "GET";
reque.Accept = "application/json";
reque.ContentType = "application/json";//application/x-www-form-urlencoded
reque.UserAgent = "Java/1.6.0_22";
reque.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
reque.Credentials = new NetworkCredential("abcd", "123456");
reque.PreAuthenticate = true;
reque.KeepAlive = true;
reque.Headers["Authorization"] = "Basic ERTGFEDCVTY=";
HttpWebResponse response = (HttpWebResponse)reque.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
using (var twitpicResponse = (HttpWebResponse)reque.GetResponse())
{
using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
List<RootObject> myojb = js.Deserialize<List<RootObject>>(objText);
DataTable dt = new DataTable();
int countvalue = myojb.Count;
for (int i = 0; i < countvalue; i++)
{
//Need to display the data in GRIDVIEW...
//FirstName =dt.Rows.Add(myojb[i].firstName).ToString();
//LastName = dt.Rows.Add(myojb[i].lastName).ToString();
and so on...
}
gvRecipient.DataSource = dt;
gvRecipient.DataBind();
}
}
}
}
catch
{
Msg.InnerHtml = "<div class='msg-error'>We are facing some technical issues in processing your request. We will make it up quickly. Please try after some time.</div>";
}
}
我的 JSON 数据
[{"firstName":"asdf","lastName":"qwer"...so on..}]
我的网格
错误:
【问题讨论】:
-
有什么原因,为什么要将 List
转换为 DataTable?您可以将 myojb 直接分配给 GridView 数据源 -
我试过那个..但无法插入值,所以我改为列表..