Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serialize two different instances in a list to a single json string

I have two types of classes:

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()
    {
    }
}

and then I have two list items.

List<ProjectClass> pc;
List<HolidayClass> hc;

I can serialize a single list with:

myJson = new JavaScriptSerializer().Serialize(pc).ToString();

or

myJson = new JavaScriptSerializer().Serialize(hc).ToString();

I want to serialize these two lists in a single json string. How can ı do this?

like image 807
user999822 Avatar asked Mar 11 '14 18:03

user999822


1 Answers

Most sensible thing to do is to create a new type for serialization or using an anonymous type:

var objects = new { HolidayClasses = hc, ProjectClasses = pc };
string result = new JavaScriptSerializer().Serialize(objects);
like image 111
Ufuk Hacıoğulları Avatar answered Sep 20 '22 22:09

Ufuk Hacıoğulları