Before start write your coding, please make sure you add reference Newtonsoft.Json. If you haven't get it, please download from here.
Define your mySQL connection first and write your query.
- MySqlConnection conn = new MySqlConnection(
- "server=localhost;" +
- "uid=xx;" +
- "pwd=xx;" +
- "database=xx;");
- MySqlCommand comm = new MySqlCommand();
- conn.Open();
- comm = conn.CreateCommand();
- comm.CommandText = "SELECT name FROM student";
- MySqlDataReader reader = comm.ExecuteReader();
- List<Student> eList = new List<Student>();
Don't forget to build constructor to get and set.
- public class Student
- {
- public string Name;
- }
- while (reader.HasRows)
- {
- if (reader.Read())
- {
- e.Name = Convert.ToString(reader["Name"]);
- eList.Add(e);
- }
- else
- {
- break;
- }
- }
Convert to JSON format.
- System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
- string ans = oSerializer.Serialize(eList);
- string script = "{\"Employee\": " + ans + "}";
- ClientScriptManager cs = Page.ClientScript;
- cs.RegisterStartupScript(Page.GetType(), "JSON", script, true);
- Response.ContentType = "application/json";
- Response.Write(script);
Check your aspx file in browser.
Sharing is caring. =)
I don't built Json file. I want to use Json data fomart to index into ElasticSearch? Absolutly using C#
ReplyDeleteCan you help me?
Thank in advance