gpt4 book ai didi

c# - 将列表中的两个不同实例序列化为单个 json 字符串

转载 作者:太空狗 更新时间:2023-10-30 01:04:41 26 4
gpt4 key购买 nike

我有两种类型的类(class):

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);

关于c# - 将列表中的两个不同实例序列化为单个 json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22333675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com