How to convert a MySQL query to JSON in C #

1

I would like to know how to convert the result of a MySQL query to JSON in C #

I do not have much knowledge in the following, but I would like the result of the query to be saved in JSON.

public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

    public void GetEmpleadoJSON()
    {
        string server = "localhost", database = "ventas", user = "root", pass = "";
        MySqlConnection conectar = new MySqlConnection("server=" + server + "; database=" + database + "; Uid=" + user + "; pwd=" + pass + ";");
        conectar.Open();
        MySqlCommand command = conectar.CreateCommand();

        //consulta select
        command.CommandText = ("SELECT 'nombre' FROM 'cliente' WHERE id_cliente=901 ");
        command.Connection = conectar;
        MySqlDataReader reader = command.ExecuteReader();

        Empleado[] emps = new Empleado[] {
        new Empleado(){
            Id=101,
            Name=reader.ToString(),
            Salary=10000
        }

        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(emps));
    }
}
    
asked by Rasimus.84 23.05.2017 в 01:09
source

1 answer

1

To serialize an object you need to use the library Newtonsoft with using Newtonsoft.Json; :

public void GetEmpleadoJSON()
{
    string json = string.Empty;
    Empleado objEmpleado = new Empleado();

    string server = "localhost", database = "ventas", user = "root", pass = "";
    string connectionString = ""server=" + server + "; database=" + database + "; Uid=" + user + "; pwd=" + pass + ";"";

    using (var conn = new MySqlConnection(connectionString))
    {
        using (var cmd = new MySqlCommand())
        {
            cmd.Connection = conn;
            cmd.CommandText = "SELECT nombre FROM cliente WHERE id_cliente = 901";
            conn.Open();
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    try
                    {
                        Empleado.Nombre = (string)reader["nombre"];
                    }
                    catch (Exception ex) {
                        //Manejo de la excepción
                    }
                }
            }
        }
    }

    json = JsonConvert.SerializeObject(objEmpleado);
    Context.Response.Write(json);
}

To serialize the object is with line json = JsonConvert.SerializeObject(objEmpleado); , so simple.

Similarly, if you manage to notice, I have changed your code a bit using contexts using , this is for the release of resources is done automatically without having to be closing connections to database or releasing resources from memory as the commands or the readers of the execution to database.

    
answered by 23.05.2017 / 02:54
source