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 on the same json line. How to do it?

+4
source share
3 answers

The most reasonable task is to create a new type to serialize or use an anonymous type:

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

EDIT: Actually, I misunderstood the question; I thought you want to serialize all the objects in one list. To serialize both lists separately in one object, look at Ufuk's answer.


Combining two lists into a list of objects:

List<object> objs = pc.Concat<object>(hc).ToList();
myJson = new JavaScriptSerializer().Serialize(objs).ToString();

, , ... a >

0

You will have to either create a class containing both lists, and then create an instance of the class and serialize it. Or you can add two lists to the dictionary and serialize it as follows:

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

Source: https://habr.com/ru/post/1531227/


All Articles