c# Extract data from mysql in json format

Viewed 341

I'm developing an application in windows form,I have json data in my mysql database ,column = data '{"money":0,"goal":0,"advantage":0}' I'm trying to pull this data into tags in the form,label1.text="money";label2.text="goal";label3.text="advantage"; I could not find enough resources like this and I am inexperienced in this regard. I uploaded the Json nouget package to my form. output ='{"money":0,"goal":0,"advantage":0}' How can I get json data as I want. Thanks for your help.

MySqlConnection baglan = new MySqlConnection("Server=localhost;Database=json;user=root;Pwd=;");
    private void Form1_Load(object sender, EventArgs e)
    {
        baglan.Open();
       MySqlCommand kom = new MySqlCommand("SELECT * FROM player_accounts", baglan);
        int count = Convert.ToInt32(kom.ExecuteScalar());
        if (count != 0)
        {

            MySqlDataReader oku = kom.ExecuteReader();
            while (oku.Read())
            {
                listBox1.Items.Add(oku["data"].ToString());

            }
            baglan.Close();
        }
    } 
1 Answers

If the JSON data is always the same, the 1st thing I would create is a model class to house the data in C# land.

So, something like this::

public class Data
{
    public decimal money { get; set; }
    public int goal { get; set; }
    public int advantage { get; set; }
}

Then, in your function, I would convert the JSON data to this new object and return from the function. For this you will need to go to nuget and install Newtonsoft.Json

Now you can write something like this:

var dbData = JsonConvert.DeserializeObject<Data>(oku["data"]);

instead of your line:

listBox1.Items.Add(oku["data"].ToString());

The function would look something like this:

private List<Data> GetDatabaseData()
{
    var resultList = new List<Data>();

    MySqlConnection baglan = new MySqlConnection("Server=localhost;Database=json;user=root;Pwd=;");
    baglan.Open();
    MySqlCommand kom = new MySqlCommand("SELECT * FROM player_accounts", baglan);
    int count = Convert.ToInt32(kom.ExecuteScalar());
    if (count != 0)
    {
        MySqlDataReader oku = kom.ExecuteReader();
        while (oku.Read())
        {
            var data JsonConvert.DeserializeObject<Data>(ku["data"].ToString());
            resultList.Add(data);
        }
        baglan.Close();
    }

    return resultList;
}

You can then use the function like this:

var dataList = GetDatabaseData();
foreach( var item in dataList )
{
    listBox1.Items.Add(item.money);
}
Related