SQL表到JSON文件

本文关键字:文件 JSON 表到 SQL | 更新日期: 2023-09-27 18:13:49

我怎样才能使这段代码我必须为我生成一个JSON文件?

现在我将值读入字符串,但我希望它自动生成文件。

 using (SqlDataReader reader = cmd.ExecuteReader())
 {
      while (reader.Read())
      {
            userinfo info = new userinfo();
            info.userid = reader.GetInt32(0);
            info.username = reader.GetValue(1).ToString();
            info.password = reader.GetValue(2).ToString();
            info.firstname = reader.GetValue(3).ToString();
            info.lastname = reader.GetValue(4).ToString();
            info.dob = reader.GetValue(5).ToString();
            info.dateregistered = reader.GetValue(6).ToString();
            JavaScriptSerializer jss = new JavaScriptSerializer();
            jsonString = jss.Serialize(info);
           //string json = JsonConvert.SerializeObject(info);
      }
 }

SQL表到JSON文件

下面的代码遍历每个读取器值并将它们添加到Dictionary中,Dictionary被添加到List中。

Dictionary将被序列化为JSON中的对象,List将被序列化为数组。

string json = string.Empty;
List<object> objects = new List<object>();
using (SqlConnection conn = new SqlConnection("connectionstring"))
{
    conn.Open();
    using (SqlCommand command = conn.CreateCommand())
    {
        command.CommandText = "SELECT * FROM USERS";
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                IDictionary<string, object> record = new Dictionary<string, object>();
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    record.Add(reader.GetName(i), reader[i]);
                }
                objects.Add(record);
            }
        }
    }
}
json = JsonConvert.SerializeObject(objects);
using (StreamWriter sw = new StreamWriter(File.Create("C:''path''file.json")))
{
    sw.Write(json);
}

可以有一个userinfo列表。然后您可以序列化该列表并将其保存到文件中。

using (SqlDataReader reader = cmd.ExecuteReader())
    {
      List<userinfo> infoList = new List<userinfo>();
      while (reader.Read())
      {
        userinfo info = new userinfo();
        info.userid = reader.GetInt32(0);
        info.username = reader.GetValue(1).ToString();
        info.password = reader.GetValue(2).ToString();
        info.firstname = reader.GetValue(3).ToString();
        info.lastname = reader.GetValue(4).ToString();
        info.dob = reader.GetValue(5).ToString();
        info.dateregistered = reader.GetValue(6).ToString();
        infoList.Add(info);
  }
  var jsonSerialiser = new System.Web.Script.Serialization.JavaScriptSerializer();
  string jsonString = jsonSerialiser.Serialize<(infoList);
  System.IO.File.WriteAllText(@"D:'userlist.json", jsonString);
}

用于回读

jsonSerialiser.Deserialize<List<userinfo>>(System.IO.File.ReadAllText(@"D:'userlist.json"));