0

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

How can I solve it?

4

3 Answers 3

3

Some of observations listed below.

Step 1: Converting a JSON string to .NET object

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.

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

]

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

]

Step 1.2: Declare string variable with replaced string as shown below

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

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

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.

Step 2.2

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

    }

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

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

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

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.

Bind the datatable with Gridview as shown below

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

step 4.1 .

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();





        }

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.

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

You have to create a class with same properties as your JSON file has and then deserialize into an instance of the class. Add it to a list and work from there with the list. Here is an example.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.