将列表中的两个不同实例序列化为单个json字符串
本文关键字:序列化 实例 单个 字符串 json 两个 列表 | 更新日期: 2023-09-27 17:49:38
我有两类:
public class HolidayClass
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public bool Active { get; set; }
public HolidayClass(int ID, string Name, DateTime StartDate, DateTime EndDate, bool Active)
{
this.ID = ID;
this.Name = Name;
this.StartDate = StartDate;
this.EndDate = EndDate;
this.Active = Active;
}
public HolidayClass()
{
}
}
public class ProjectClass
{
public int ID { get; set; }
public string NetsisID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public bool Active { get; set; }
public ProjectClass(int ID, string NetsisID, string Name, string Address, bool Active)
{
this.ID = ID;
this.NetsisID = NetsisID;
this.Name = Name;
this.Address = Address;
this.Active = Active;
}
public ProjectClass()
{
}
}
然后我有两个列表项。
List<ProjectClass> pc;
List<HolidayClass> hc;
我可以序列化一个列表:
myJson = new JavaScriptSerializer().Serialize(pc).ToString();
或
myJson = new JavaScriptSerializer().Serialize(hc).ToString();
我想在一个json字符串中序列化这两个列表。你怎么能这么做?
最明智的做法是为序列化或使用匿名类型创建一个新类型:
var objects = new { HolidayClasses = hc, ProjectClasses = pc };
string result = new JavaScriptSerializer().Serialize(objects);
您必须创建一个包含这两个列表的类,然后实例化该类并将其序列化。或者您可以将这两个列表添加到字典中,并像这样序列化它:
Dictionary<string, List<object>> sample = new Dictionary<string, List<object>>() { { "pc", pc }, { "hc", hc } };
myJson = new JavaScriptSerializer().Serialize(sample).ToString();