【问题标题】:how to bind json to listview control如何将json绑定到listview控件
【发布时间】:2017-02-16 20:58:45
【问题描述】:

谁能帮助我如何将 JSON 数据绑定到列表视图控件。 JSON就是这种格式,是重新序列化的数据表:

[  
   {  
      "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"
   }
]

我该如何解决?

【问题讨论】:

标签: c# asp.net json vb.net


【解决方案1】:

您必须创建一个与 JSON 文件具有相同属性的类,然后反序列化为该类的实例。将其添加到列表中并从那里使用列表。这是一个例子。

class Person
{
    public int Ch_ID { get; set; }
    public int User_id{ get; set; }
    public string Ch_Name { get; set; }
    // all properties...
    public override string ToString()
    {
        return string.Format("User ID: {0} \n Name: {1}", User_id, Ch_Name);
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Parsing into a class from JSON file using JavaScriptSerializer class
        string path = "C:\\path\\";
        // Deserialize JSON from file.
        String JSONfile = File.ReadAllText(path + "JSON.json");
        JavaScriptSerializer ser = new JavaScriptSerializer();
        Person p1 = ser.Deserialize<Person>(JSONfile);
        Console.WriteLine(p1);

        List<Person> newList = new List<Person>();
        // add instance of the class to the list
        newList.Add(p1);
        // do work whith your list...
    }
}

【讨论】:

    【解决方案2】:

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

    第 1 步:将 JSON 字符串转换为 .NET 对象

    一般JSON字符串包含很多双引号("),但在C#中双引号有特殊含义,表示字符串的开始和结束。

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

    [
    
     {"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 字符串如下所示。

    [
    
     {\"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 中,同样的语句也可以多行声明,如下所示。

     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\"}]";
    

    第二步

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

    步骤 2.2

    以属性的形式声明一个具有上述JSON字符串字段的类,如下所示(为简单起见,StartTime被声明为字符串而不是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 传递,第二个参数我们必须指定结果对象的类型(即员工列表)。使用员工列表进行类型转换并存储在列表中雇员对象如下所示。

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

    第三步

    将员工列表转换为数据表并绑定到数据网格(使用数据网格而不是列表视图,因为它具有更多功能,例如绑定字段和模板字段

    DataTable dt1=  ConvertToDatatable(listEmployee);
    

    步骤 3.1

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

    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;
            }
    

    第四步

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

    <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>
    

    第四步。

    如下图将数据表与Gridview绑定

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

    步骤 4.1。

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

     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 字符串,程序将无法按预期运行。

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

    【讨论】:

      【解决方案3】:
      string json = "[{\"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\"}]";
      
      var obj = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(json);
      
      List<Employee> employees = (obj).Select(x => new Employee
      {
          ID = (string)x["ID"],
          UserID = (string)x["UserID"]
      }).ToList();
      
      foreach (var emp in employees)
      {
          lvNewData.Items.Add(emp.ID);
          // add other things
      }   
      

      【讨论】:

        猜你喜欢
        • 2014-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-23
        • 2018-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多