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

时间:2014-03-11 18:35:44

标签: c# json serialization

我有两种类型:

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字符串中序列化这两个列表。 怎么能这样做?

2 个答案:

答案 0 :(得分:5)

最明智的做法是为序列化或使用匿名类型创建新类型:

var objects = new { HolidayClasses = hc, ProjectClasses = pc };
string result = new JavaScriptSerializer().Serialize(objects);

答案 1 :(得分:0)

您必须创建一个包含两个列表的类,然后实例化该类并对其进行序列化。或者您可以将两个列表添加到字典中并将其序列化为:

Dictionary<string, List<object>> sample = new Dictionary<string, List<object>>() { { "pc", pc }, { "hc", hc } };
myJson = new JavaScriptSerializer().Serialize(sample).ToString();