Search code examples
c#jsonjavascriptserializer

c# using JavaScriptSerializer serializer in while loop and returning to client side to Json.Parse. Getting a error


Could anyone give me a step to solve this error in getting a output. New to coding.

Step 1: Using Json/Javascript calling a method which is in .cs file(c#)

 var markers = JSON.parse('<%=ConvertDataTabletoString("NewGetTaskWorkPercentage1",null) %>');

Step 2:

.cs file code for method ConvertDataTabletoString
 public string ConvertDataTabletoString(string Sql, string prjno)
        {
            //var qprojectno = Request.QueryString["ProjectNo"].ToString();
            param1.Value = "P-2020-0009";  //aspx hidden field
           DataTable dt = new DataTable();
            using (con = new SqlConnection(connectionString))
            {
                using (cmd = new SqlCommand(Sql, con))
                {
                    string connetionString = "Data Source = ; Initial Catalog = DashBoardDB; User ID = ; Password = ";
                    SqlConnection connection = new SqlConnection(connetionString);
                    connection.Open();
                     string sql1 = "SELECT InstanceId,Module,SubModule,Process FROM Xtable WHERE ProjectNo=" + "'" + param1.Value + "'"+ "and instanceid='aabed4df-3e91-41c0-8788-2e7d31eecfd8'";

                    SqlCommand command = new SqlCommand(sql1, connection);
                    command.CommandTimeout = 600;
                    SqlDataReader dataReader = command.ExecuteReader();
                  serializedResult = " ";
                    while (dataReader.Read())
                    {
                       string strInsId = " ";
                        string strProcess = "";
                      strInsId = dataReader["InstanceId"].ToString();
                       con.Open();
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("@ProjectNo", prjno));
                        cmd.Parameters.Add(new SqlParameter("@InstanceId", strInsId));
                        sda = new SqlDataAdapter(cmd);
                        sda.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                        Dictionary<string, object> row;

                        foreach (DataRow dr in dt.Rows)
                        {
                            Console.WriteLine(dr + " " + dt.Rows);
                            row = new Dictionary<string, object>();
                            foreach (DataColumn col in dt.Columns)
                            {
                                 row.Add(col.ColumnName, dr[col]); 
                            }
                            rows.Add(row);
                        }

                        serializedResult = serializer.Serialize(rows);
                        serializedResult += serializer.Serialize(rows); **two times concatenating**
                        con.Close();}
                       dataReader.Close();
                    command.Dispose();
                    connection.Close();
                    return serializedResult;
                   }
 }

        }

Step 3: Image Attached

enter image description here

enter image description here

enter image description here

In client side how to split this values into arrays. I required output like this. How can i get the output in array and the length of the array at client side. Thanks

Array 1:

 [{"Task":"Feature 1.1.3","OverallSubtaskDuration":17.00,"ActualStart":"2019/10/18","ActualEnd":"2020/03/13","OverallSubtaskPercentage":283.33},
  {"Task":"Feature 1.1.3","OverallSubtaskDuration":8.00,"ActualStart":"2019/10/18","ActualEnd":"2019/10/25","OverallSubtaskPercentage":133.33},
  {"Task":"Feature 1.1.3","OverallSubtaskDuration":3.00,"ActualStart":"2020/03/11","ActualEnd":"2020/03/13","OverallSubtaskPercentage":50.00},
  {"Task":"Feature 1.1.3","OverallSubtaskDuration":3.00,"ActualStart":"2019/10/27","ActualEnd":"2019/10/29","OverallSubtaskPercentage":50.00}]

Array 2:

[{"Task":"Feature 1.1.3","OverallSubtaskDuration":17.00,"ActualStart":"2019/10/18","ActualEnd":"2020/03/13","OverallSubtaskPercentage":283.33},
 {"Task":"Feature 1.1.3","OverallSubtaskDuration":8.00,"ActualStart":"2019/10/18","ActualEnd":"2019/10/25","OverallSubtaskPercentage":133.33},
 {"Task":"Feature 1.1.3","OverallSubtaskDuration":3.00,"ActualStart":"2020/03/11","ActualEnd":"2020/03/13","OverallSubtaskPercentage":50.00},
 {"Task":"Feature 1.1.3","OverallSubtaskDuration":3.00,"ActualStart":"2019/10/27","ActualEnd":"2019/10/29","OverallSubtaskPercentage":50.00}]

Solution

  • The JSON result has to be either an object or an array.

    The result you are creating is two arrays back to back and therefore not valid JSON and you can test this by using an online validator such as https://jsonlint.com/

    So you either need to create one large array with all the elements from both your other arrays, or you need to wrap the two arrays into a wrapper object.

    The simplest for you, as you have already are using a List<>, is to combine this with itself and return the result.

    //Add the "rows" list to itself, so you double it.
    rows.AddRange(rows);
    serializedResult = serializer.Serialize(rows);
    ...
    return serializedResult;
    

    If you need to keep the lists distinct then you have to use a wrapper object. Like this;

    public class Wrapper
    {
        public List<Dictionary<string, object>> Array1 { get; set;  }
        public List<Dictionary<string, object>> Array2 { get; set; }
    }
    

    Then you serialise like this

    serializedResult = serializer.Serialize(new Wrapper() { Array1 = rows, Array2 = rows };);
    ...
    return serializedResult;