如何从dictionary序列化类对象键

本文关键字:序列化 对象 int dictionary class | 更新日期: 2023-09-27 18:12:21

我将类对象存储为键,将int存储为值。我想将字典转换为json字符串,但没有成功。我正在使用NewtonSoft的json转换。这里是我的代码

 SeatInfo seatInfo = new SeatInfo() { SeatNo = 1, Status = true, NickName = "Suresh", UserID = "sss" };
Dictionary<SeatInfo, int> dic = new Dictionary<SeatInfo, int>();
dic.Add(seatInfo, 40);

string json = JsonConvert.SerializeObject(dic, Formatting.Indented, new JsonSerializerSettings
  {
      TypeNameHandling = TypeNameHandling.None,
      TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
  });

这个代码的结果是,

{"SignalRServer.SeatInfo":40}

如何将类属性转换为字符串。提前感谢

如何从dictionary<class & int>序列化类对象键

我找到了答案。但我不确定这是否正确。我只是将dictionary对象转换为List。我得到了类属性是键,int是值。

    string json = JsonConvert.SerializeObject(dic.ToList(), Formatting.Indented, new JsonSerializerSettings
  {
      TypeNameHandling = TypeNameHandling.None,
      TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
  });
这里我只是将dic对象转换为dic. tolist ()。输出是,
 {
    "Key": {
      "SeatNo": 1,
      "UserID": "sss",
      "NickName": "Suresh",
      "Status": true
    },
    "Value": 40
  }

如果我错了请指教,谢谢

在Webservice中运行以下代码:

   SqlConnection con = new SqlConnection("Here Copy your connection string");
    [WebMethod]
    [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
    public string GetData()
    {
        var json = "";
        List<Dictionary<string, object>> lst = new List<Dictionary<string, object>>();
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tbldemo",con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        con.Close();
        foreach (DataRow row in dt.Rows)
        {
            Dictionary<string, object> lst1 = new Dictionary<string, object>();
            foreach (DataColumn dc in dt.Columns )
            {
                lst1.Add(dc.ColumnName,row[dc]);
            }
            lst.Add(lst1);
        }
        JavaScriptSerializer js = new JavaScriptSerializer();
        json = js.Serialize(lst);
        return json;
    }