locked
JsonConvert.SerializeObject(request) while reader.Read RRS feed

  • Question

  • User1069198773 posted

    Hi. So using this code I'm converting to Json, but I don't like it, because It's not a correct way to convert data to Json.

    string ConnectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
                SqlConnection con = new SqlConnection(ConnectionString);
                SqlCommand cmd = new SqlCommand(
                        "select *  from table where id_glavni_mavzu = @id_glvni_mavzu", con);
    
                SqlParameter param = new SqlParameter();
                param.ParameterName = "@id_glvni_mavzu";
                param.Value = id;
    
                cmd.Parameters.Add(param);
    
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                Response.Write("[");
                int count = 0;
                while (reader.Read())
                {
                    if (count == 0)
                    {
                        Response.Write("{");
    
                    }
                    else
                    {
                        Response.Write(",{");
    
                    }
                    Response.Write("\"id\":" + reader["id"].ToString() + ",\"ru\":" + "\"" + reader["rus"] + "\"" + ",\"tj\":" + "\"" + reader["taj"] + "\"}");
                    count++;
                }
                Response.Write("]");
                reader.Close();
                con.Close();

    And I have also this code to convert a simple data to Json.

    var request = new String[2];
            request[0] = "Name";
            request[1] = "Occupaonti";
    
            var json = JsonConvert.SerializeObject(request);
            Response.Write(json.ToString());

    How is it possible to use the second code to convert my data to Json while reader.Read ?

    Monday, March 23, 2020 11:23 AM

All replies

  • User475983607 posted

    Pretty simply.  Use the data reader to populate a type array where the type properties matches the select columns.  You did not share the table column names and types but if we use the JSON string the class might look like the following.

    public class MyModel 
    {
       public int id { set; set; }
       public string ru { set; set; }
       public string tj { set; set; }
    }

    Anyway, populating a strong type using a data reader is very common and there are a lot of examples online.

    Monday, March 23, 2020 11:38 AM
  • User1535942433 posted

    Hi jfr,

    Accroding to your description,as far as I think,I suggest you could create a new class to stored data.Then you could read data by data reader.

    More details,you could refere to below codes:

    ASPX:

    <div>
                <asp:TextBox ID="Id" runat="server"></asp:TextBox>
                <asp:TextBox ID="Name" runat="server" />
                <asp:TextBox ID="Type" runat="server" />
                <asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" /><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            </div>

    Code-behind:

    protected void btnSubmit_Click(object sender, EventArgs e)
            {
                string constring = ConfigurationManager.ConnectionStrings["aspnet-TestApplicationWithDatabase-20190820030542"].ConnectionString;
                SqlConnection con = new SqlConnection(constring);
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT * FROM gv WHERE Type=@Type", con);
                cmd.Parameters.AddWithValue("@Id",Int32.Parse(Id.Text.Trim()));
                cmd.Parameters.AddWithValue("@Name", Name.Text.ToString());
                cmd.Parameters.AddWithValue("@Type", Type.Text.ToString());
                SqlDataReader reader = cmd.ExecuteReader();
                List<nnn> records = new List<nnn>();
                while (reader.Read())
                {
                    nnn record = new nnn();
                    record.Id = Convert.ToInt32(reader["Id"].ToString());
    record.Name = reader["Name"].ToString();
    record.Type = reader["Type"].ToString(); records.Add(record); } reader.Close(); cmd.ExecuteNonQuery(); Label1.Text = "{\"data\":" + JsonConvert.SerializeObject(records) + "}"; con.Close(); }

    class.cs:

    public class nnn
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Type { get; set; }
        }

    Result:

    Best regards,

    Yijing Sun

    Tuesday, March 24, 2020 6:08 AM