如何将json绑定到listview控件 [英] how to bind json to listview control

查看:76
本文介绍了如何将json绑定到listview控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以帮助我如何将JSON数据绑定到列表视图控件.JSON是这种格式,它是重新序列化的数据表:

Can anyone help me with how I can bind a JSON data to a list view control. The JSON is in this format, which is a re-serialized data table:

[  
   {  
      "Ch_ID":"27",
      "User_id":"1",
      "Ch_Name":"test1",
      "Ch_Description":"test1description",
      "Ch_Starttime":""
   },
   {  
      "Ch_ID":"29",
      "User_id":"1",
      "Ch_Name":"w",
      "Ch_Description":"ww",
      "Ch_Starttime":"12"
   },
   {  
      "Ch_ID":"30",
      "User_id":"1",
      "Ch_Name":"qq",
      "Ch_Description":"qqqdescription",
      "Ch_Starttime":"1222"
   },
   {  
      "Ch_ID":"31",
      "User_id":"1",
      "Ch_Name":"v",
      "Ch_Description":"vv",
      "Ch_Starttime":"1"
   },
   {  
      "Ch_ID":"32",
      "User_id":"1",
      "Ch_Name":"n",
      "Ch_Description":"nnnn",
      "Ch_Starttime":"111"
   }
]

我该如何解决?

推荐答案

下面列出了一些观察结果.

Some of observations listed below.

一般而言,JSON字符串包含许多双引号(),但在 C#中,双引号具有特殊含义,它指示字符串的开头和结尾.

In general JSON string contains lot of double quotes("), but in C# double quotes having special meaning and it indicates beginning and end of string.

如下所示,给定的json字符串包含很多双引号,但这些都是该字符串的一部分,我们不想将其视为字符串的开头和结尾,因此需要对其进行转义.

As listed below, given json string contains lots of double quotes but those are the parts of that string and we don't want to treat that as beginning and end of the string and we need to escape that.

[

 {"Ch_ID":"27","User_id":"1","Ch_Name":"test1","Ch_Description":"test1description","Ch_Starttime":""},

 {"Ch_ID":"29","User_id":"1","Ch_Name":"w","Ch_Description":"ww","Ch_Starttime":"12"},

 {"Ch_ID":"30","User_id":"1","Ch_Name":"qq","Ch_Description":"qqqdescription","Ch_Starttime":"1222"},
 {"Ch_ID":"31","User_id":"1","Ch_Name":"v","Ch_Description":"vv","Ch_Starttime":"1"},
 {"Ch_ID":"32",User_id":"1","Ch_Name":"n","Ch_Description":"nnnn","Ch_Starttime":"111"}

]

步骤1.1:将双引号()替换为反斜杠双引号(").

按CTRL + H并将替换为".替换后的json字符串如下所示.

Step 1.1: Replace double quotes(") with backslash double quotes(").

Press CTRL+H and replace " with ". Replaced json string is shown below.

[

 {\"Ch_ID\":\"27\",\"User_id\":\"1\",\"Ch_Name\":\"test1\",\"Ch_Description\":\"test1description\",\"Ch_Starttime\":\"\"},

 {\"Ch_ID\":\"29\",\"User_id\":\"1\",\"Ch_Name\":\"w\",\"Ch_Description\":\"ww\",\"Ch_Starttime\":\"12\"},

 {\"Ch_ID\":\"30\",\"User_id\":\"1\",\"Ch_Name\":\"qq\",\"Ch_Description\":\"qqqdescription\",\"Ch_Starttime\":\"1222\"},
 {\"Ch_ID\":\"31\",\"User_id\":\"1\",\"Ch_Name\":\"v\",\"Ch_Description\":\"vv\",\"Ch_Starttime\":\"1\"},
 {\"Ch_ID\":\"32\",User_id\":\"1\",\"Ch_Name\":\"n\",\"Ch_Description\":\"nnnn\",\"Ch_Starttime\":\"111\"}

]

步骤1.2:声明具有替换字符串的字符串变量,如下所示

 //Showing stringJSON in single line
// First double quotes in below line indicates beginning of JSON string and last    Double quotes indicate end of the string
// Other Doubles quotes are part of the string , they are precededby backslash so we are escaping that double quotes

 string jsonString = "[{\"ID\":\"27\",\"UserID\":\"1\",\"Name\":\"test1\",\"Description\":\"test1description\",\"StartTime\":\"\"},{\"ID\":\"29\",\"UserID\":\"1\",\"Name\":\"w\",\"Description\":\"ww\",\"StartTime\":\"12\"},{\"ID\":\"30\",\"UserID\":\"1\",\"Name\":\"qq\",\"Description\":\"qqqdescription\",\"StartTime\":\"1222\"},{\"ID\":\"31\",\"UserID\":\"1\",\"Name\":\"v\",\"Description\":\"vv\",\"StartTime\":\"1\"},{\"ID\":\"32\",\"UserID\":\"1\",\"Name\":\"n\",\"Description\":\"nnn\",\"StartTime\":\"111\"}]";

在Visual Studio IDE中,也可以在多行中声明相同的语句,如下所示.

In Visual studio IDE Same statements can also be declared in multiline as shown below.

 string jsonString = "[{\"ID\":\"27\",\"UserID\":\"1\",\"Name\":\"test1\",\"Description\":\"test1description\",\"StartTime\":\"\"} " +
                 " ,"  + " {\"ID\":\"29\",\"UserID\":\"1\",\"Name\":\"w\",\"Description\":\"ww\",\"StartTime\":\"12\"}" +
                "," + " {\"ID\":\"30\",\"UserID\":\"1\",\"Name\":\"qq\",\"Description\":\"qqqdescription\",\"StartTime\":\"1222\"}" +
                "," + "{\"ID\":\"31\",\"UserID\":\"1\",\"Name\":\"v\",\"Description\":\"vv\",\"StartTime\":\"1\"}" +
                "," + "{\"ID\":\"32\",\"UserID\":\"1\",\"Name\":\"n\",\"Description\":\"nnn\",\"StartTime\":\"111\"}]";

步骤2

我们要将上面的JSON字符串转换为.net对象.JSON字符串包含5个雇员对象,因此请使用System.Web.Script.Serialization命名空间中可用的JavaScriptSerializer的Deserialize()方法构造一个雇员对象列表.

Step 2

We want to convert the above JSON string to .net Object. The JSON string contains 5 employee objects, so construct a list of employee object for that make use of Deserialize() method of JavaScriptSerializer which is available in System.Web.Script.Serialization namespace.

以属性形式声明具有上述JSON字符串字段的类,如下所示(为简单起见,StartTime声明为字符串而不是DateTime)

Declare a class with above mentioned fields of JSON string in the form of properties as shown below(for simplicity StartTime is declared as string instead of DateTime)

public class Employee
    {

        public string ID { get; set; }
        public string UserID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string StartTime { get; set; }

    }

步骤2.3

创建一个JavaScriptSerializer实例,该实例具有两个参数并将第一个参数传递为Jsonstring,第二个参数我们必须指定结果对象的类型(即,雇员列表).员工对象,如下所示.

Step 2.3

create an instance of JavaScriptSerializer, having two parameter and passing the first parameter as Jsonstring, second parameter we have to specify the type of the resulting object( i.e list of employees).Type cast with list of employee and store in list of employee object as shown below.

JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
List<Employee> listEmployee=  (List<Employee>)javaScriptSerializer.Deserialize(jsonString, typeof(List<Employee>));

步骤3

将雇员列表列表转换为数据表并绑定到数据网格(使用datagrid而不是listview,因为它具有诸如boundfields和TemplateFields之类的更多功能

Step 3

Convert list of list of Employees to a datatable and bind to a datagrid(using datagrid instead of listview because it is having more features such as boundfields and TemplateFields

DataTable dt1=  ConvertToDatatable(listEmployee);

步骤3.1

下面列出了转换为数据表的功能

Step 3.1

Function to convert to datatable is listed below

static DataTable ConvertToDatatable(List<Employee> list)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("ID");
            dt.Columns.Add("UserID");
            dt.Columns.Add("Name");
            dt.Columns.Add("Description");
            dt.Columns.Add("StartTime");

            foreach (var item in list)
            {
                var row = dt.NewRow();

                row["ID"] = item.ID;
                row["UserID"] = item.UserID;
                row["Name"] = item.Name;
                row["Description"] = item.Description;
                row["StartTime"] = item.StartTime;


                dt.Rows.Add(row);
            }

            return dt;
        }

步骤4

声明一个DataGrid..aspx页面如下所示

Step 4

Declare a DataGrid . .aspx page looks like the following

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3"  BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellSpacing="2">
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" />
                <asp:BoundField DataField="UserID" HeaderText="User  ID" />
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:BoundField DataField="Description" HeaderText="Description" />
                <asp:BoundField DataField="StartTime" HeaderText="Start Time" />
               </Columns>
            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
            <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FFF1D4" />
            <SortedAscendingHeaderStyle BackColor="#B95C30" />
            <SortedDescendingCellStyle BackColor="#F1E5CE" />
            <SortedDescendingHeaderStyle BackColor="#93451F" />
        </asp:GridView>

Step4.

使用Gridview绑定数据表,如下所示

Step4.

Bind the datatable with Gridview as shown below

GridView1.DataSource = dt1;GridView1.DataBind();

GridView1.DataSource = dt1; GridView1.DataBind();

所有功能都在页面上的按钮单击事件上执行,如下所示:

All the functionalities are performed on button click event in the page as shown below:

 protected void Button1_Click(object sender, EventArgs e)
        {


            //Showing stringJSON in single line
            // First double quotes in below line indicates beginning of JSON string and last Double quotes indicate end of the string
            // Other Doubles quotes are part of the string , they are precededby backslash so we are escaping that double quotes
            //string jsonString = "[{\"ID\":\"27\",\"UserID\":\"1\",\"Name\":\"test1\",\"Description\":\"test1description\",\"StartTime\":\"\"},{\"ID\":\"29\",\"UserID\":\"1\",\"Name\":\"w\",\"Description\":\"ww\",\"StartTime\":\"12\"},{\"ID\":\"30\",\"UserID\":\"1\",\"Name\":\"qq\",\"Description\":\"qqqdescription\",\"StartTime\":\"1222\"},{\"ID\":\"31\",\"UserID\":\"1\",\"Name\":\"v\",\"Description\":\"vv\",\"StartTime\":\"1\"},{\"ID\":\"32\",\"UserID\":\"1\",\"Name\":\"n\",\"Description\":\"nnn\",\"StartTime\":\"111\"}]";
            //Showing stringJSON in multi  line
            string jsonString = "[{\"ID\":\"27\",\"UserID\":\"1\",\"Name\":\"test1\",\"Description\":\"test1description\",\"StartTime\":\"\"} " +
                 " ,"  + " {\"ID\":\"29\",\"UserID\":\"1\",\"Name\":\"w\",\"Description\":\"ww\",\"StartTime\":\"12\"}" +
                "," + " {\"ID\":\"30\",\"UserID\":\"1\",\"Name\":\"qq\",\"Description\":\"qqqdescription\",\"StartTime\":\"1222\"}" +
                "," + "{\"ID\":\"31\",\"UserID\":\"1\",\"Name\":\"v\",\"Description\":\"vv\",\"StartTime\":\"1\"}" +
                "," + "{\"ID\":\"32\",\"UserID\":\"1\",\"Name\":\"n\",\"Description\":\"nnn\",\"StartTime\":\"111\"}]";


          JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
         List<Employee> listEmployee=  (List<Employee>)javaScriptSerializer.Deserialize(jsonString, typeof(List<Employee>));

            // convert list of employees to datatable

          DataTable dt1=  ConvertToDatatable(listEmployee);


            // Bind to datagrid 
            GridView1.DataSource = dt1;
            GridView1.DataBind();





        }

注意:使用JSON字符串时,检查JSON字符串的有效性很重要.如果未提供有效的JSOn字符串,则程序将按预期运行.

Note : While Working with JSON string it is important to check the validity of JSON string . If valid JSOn sting is not given the program won' work as expected.

在线工具jsonformatter可用于检查JSON字符串的有效性.( https://jsonformatter.curiousconcept.com/)

Online tool jsonformatter can be used to check validity of JSON String.(https://jsonformatter.curiousconcept.com/)

这篇关于如何将json绑定到listview控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆